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