Question

Based on Wikipedia example for Delegation Pattern the following sample code is offered. But I also have my version of code, that just have minor changes. I want to know which code is better/(more flexible) and why?

Thank you in advance.

Wikipedia Code

    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()
        }
    }

My Code (all classes are the same)

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()
        }
    }
Was it helpful?

Solution

Your code is not using the delegation pattern at all, you're just calling the methods on the implementing classes directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top