代码之家  ›  专栏  ›  技术社区  ›  Rational Redneck

Java结构化方法链接

  •  0
  • Rational Redneck  · 技术社区  · 3 年前

    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");
    

    但是我该如何限制可以调用哪些方法呢?例如制作 逻辑一 逻辑二 逻辑一 子逻辑two 逻辑二 具有 像这样在他们之间分享。

    Example obj = new Example;
    
    obj.logicOne("inputOne").subLogicOne("subInputOne");
    obj.logicTwo("inputTwo").subLogicTwo("subInputTwo");
    
    obj.logicOne("inputOne").subLogicThree("subInputThree");
    obj.logicTwo("inputTwo").subLogicThree("subInputThree");
    
    1 回复  |  直到 3 年前
        1
  •  5
  •   Sweeper    3 年前

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

    // 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*/);
    }
    

    然后,您可以让调用方创建 Example Logicable 而不是 new Example() logicOne logicTwo 实例 当然

    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
    

    逻辑一 逻辑二 SubLogicOneAble SubLogicTwoAble 实例 应更改以符合接口:

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