gpt4 book ai didi

Java 结构化方法链接

转载 作者:行者123 更新时间:2023-12-05 01:22:57 25 4
gpt4 key购买 nike

关于在 Java 中使用对象的一些问题。假设我有以下类(class)。

public class Example {

private String ex1 = new String();
private String ex2 = new String();
private int varOne;

public Example logicOne(/*Input variables*/) {
// Do logic
return this;
}

public Example logicTwo(/*Input variables*/) {
// Do logic
return this;
}

public int subLogicOne(/*Input variables*/) {
return varOne;
}

public int subLogicTwo(/*Input variables*/) {
return varTwo;
}

public int subLogicThree(/*Input variables*/) {
return varThree;
}
}

我知道将方法类型设置为类名并使用return this 将允许我在像这样调用类对象时链接方法。

Example obj = new Example;
obj.logicOne("inputOne").logicTwo("inputTwo");

但是我该如何限制哪些方法可以被调用呢?例如,使 logicOnelogicTwo 互斥,并将 subLogicOne 限制为 logicOnesubLogicTwologicTwosubLogicThree 像这样在它们之间共享。

Example obj = new Example;

obj.logicOne("inputOne").subLogicOne("subInputOne");
obj.logicTwo("inputTwo").subLogicTwo("subInputTwo");

obj.logicOne("inputOne").subLogicThree("subInputThree");
obj.logicTwo("inputTwo").subLogicThree("subInputThree");

最佳答案

可以使用接口(interface)来划分方法。

// you can probably come up with better names, taking your real situation into account
interface Logicable {
SubLogicOneAble logicOne(/*same input variables as logicOne*/);
SubLogicTwoAble logicTwo(/*same input variables as logicTwo*/);
}

interface SubLogicThreeAble {
int subLogicThree(/*same input variables as subLogicThree*/);
}

interface SubLogicOneAble extends SubLogicThreeAble {
int subLogicOne(/*same input variables as subLogicOne*/);
}

interface SubLogicTwoAble extends SubLogicThreeAble {
int subLogicTwo(/*same input variables as subLogicTwo*/);
}

然后,您可以让调用者通过返回 Logicable 而不是 new Example() 的工厂方法创建 Example 的实例。这样,调用者可以调用的第一个方法只有 logicOnelogicTwo,当然,除非它们显式转换为 Example

class Example implements SubLogicOneAble, SubLogicTwoAble, Logicable {
private Example() {}

// could also consider putting this in Logicable and calling it newLogicable (?)
public static Logicable newExample() {
return new Example();
}
Example.newExample().subLogicOne() // compiler error

另请注意,我更改了 logicOnelogicTwo 以分别返回 SubLogicOneAbleSubLogicTwoAble。这是为了确保调用者只能在这些方法的返回值上调用某些方法(同样,除非它们显式转换)。 Example 中的签名应更改为与接口(interface)一致:

public SubLogicOneAble logicOne (/*Input variables*/){
// Do logic
return this;
}

public SubLogicTwoAble logicTwo (/*Input variables*/){
// Do logic
return this;
}

关于Java 结构化方法链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73172769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com