繁体   English   中英

Java 结构化方法链接

[英]Java Structured Method Chaining

关于使用 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;
    }
}

我知道将方法类型设置为 class 名称并使用return 这将允许我在调用 class object 时链接方法。

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

但是我将如何限制可以调用哪些方法呢? 例如,使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");

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

// 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的工厂方法创建Example的实例,而不是new 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM