Java结构化方法链接



关于在java中处理对象的问题。假设我有下面的课。

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;
}
}

我知道将方法类型设置为类名并使用返回这个将允许我在调用类对象时链接方法

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

但是我该如何限制可以调用哪些方法呢?例如,使logicOnelogicTwo互斥,并将subLogicOne限制为logic一,将subLogicTwo限制为logic二

Example obj = new Example;
obj.logicOne("inputOne").subLogicOne("subInputOne");
obj.logicTwo("inputTwo").subLogicTwo("subInputTwo");
obj.logicOne("inputOne").subLogicThree("subInputThree");
obj.logicTwo("inputTwo").subLogicThree("subInputThree");

您可以使用接口来划分方法。

// 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中的签名应更改为与接口一致:

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

最新更新