delegation example regarding java context

后端 未结 4 2158
情话喂你
情话喂你 2020-12-14 02:03

What is delegation in Java? Can anyone give me a proper example?

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 02:16

    If you're referring to the delegation pattern, wikipedia has a great example, written in java.

    I believe the longer example of the page above is the best one:

    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 {
        // delegation
        I i = new A();
    
        public void f() { i.f(); }
        public void g() { i.g(); }
    
        // normal attributes
        void toA() { i = new A(); }
        void toB() { i = new B(); }
    }
    
    
    public class Main {
        public static void main(String[] args) {
            C c = new C();
            c.f();     // output: A: doing f()
            c.g();     // output: A: doing g()
            c.toB();
            c.f();     // output: B: doing f()
            c.g();     // output: B: doing g()
        }
    }
    

提交回复
热议问题