【问题标题】:What is the differences between these two code sample for delegation这两个委托代码示例有什么区别
【发布时间】:2013-11-23 02:21:08
【问题描述】:

基于Delegation Pattern 的维基百科示例,提供了以下示例代码。 但我也有我的代码版本,只是有细微的变化。我想知道哪个代码更好/(更灵活)以及为什么?

提前谢谢你。

维基百科代码

    interface I {
    void f();
    void g();
}

class A implements I {
    public void f() { System.out.println("A: doing f()"); }
    public void g() { System.out.println("A: doing g()"); }
}

class B implements I {
    public void f() { System.out.println("B: doing f()"); }
    public void g() { System.out.println("B: doing g()"); }
}


    class C implements I {
        I i = null;
        // delegation
        public C(I i){ this.i = i; }
        public void f() { i.f(); }
        public void g() { i.g(); }

        // normal attributes
        public void to(I i) { this.i = i; }
    }



    public class Main {
        public static void main(String[] args) {
            C c = new C(new A());
            c.f();     // output: A: doing f()
            c.g();     // output: A: doing g()
            c.to(new B());
            c.f();     // output: B: doing f()
            c.g();     // output: B: doing g()
        }
    }

我的代码(所有类都一样)

public class Main {
        public static void main(String[] args) {
            //C c = new C(new A());
            I ii = new A();
            ii.f();     // output: A: doing f()
            ii.g();     // output: A: doing g()
            //c.to(new B());
            ii = new B();
            ii.f();     // output: B: doing f()
            ii.g();     // output: B: doing g()
        }
    }

【问题讨论】:

    标签: design-patterns delegation


    【解决方案1】:

    您的代码根本没有使用委托模式,您只是直接调用实现类的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 2020-03-29
      • 2018-04-16
      • 2012-01-30
      • 1970-01-01
      相关资源
      最近更新 更多