Java 结构化方法链接

Rat*_*eck 3 java methods object

请教一个关于在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道将方法类型设置为类名并使用return this将允许我在调用类对象时链接方法,如下所示。

Example obj = new Example;
obj.logicOne("inputOne").logicTwo("inputTwo");
Run Code Online (Sandbox Code Playgroud)

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

Example obj = new Example;

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

obj.logicOne("inputOne").subLogicThree("subInputThree");
obj.logicTwo("inputTwo").subLogicThree("subInputThree");
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 6

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

// 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*/);
}
Run Code Online (Sandbox Code Playgroud)

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

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();
    }
Run Code Online (Sandbox Code Playgroud)
Example.newExample().subLogicOne() // compiler error
Run Code Online (Sandbox Code Playgroud)

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

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

public SubLogicTwoAble logicTwo (/*Input variables*/){
    // Do logic
    return this;
}
Run Code Online (Sandbox Code Playgroud)