【问题标题】:Is it possible to detect if fluent interface was called for the first time?是否可以检测是否第一次调用了流畅的接口?
【发布时间】:2017-07-29 20:02:27
【问题描述】:

假设我有一堂课:

class A {
    public A fun() {
        System.out.println("a");
        return this;
    }   
}

还有一个场景:

A a = new A();
a.fun().fun().fun().fun();
a.fun().fun();

是否有可能在每个顺序调用的第一次调用中打印附加消息而不添加类似.start()/.finalize() 之类的内容?

【问题讨论】:

    标签: java fluent-interface


    【解决方案1】:

    你可以这样做:

    public class A {
    
        public A fun() {
            System.out.println("A");
            return new AA();
        }
    
        private class AA extends A {
            @Override
            public A fun() {
                System.out.println("AA");
                return this;
            }
        }
    
        public static void main(String[] args) {
            A a = new A();
            a.fun();
            a.fun().fun();
            a.fun().fun().fun();
        }
    }
    

    输出:

    A
    A
    AA
    A
    AA
    AA
    

    【讨论】:

    • 哇 :D 我觉得我做梦太深了。不错。
    猜你喜欢
    • 1970-01-01
    • 2022-01-12
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多