And*_*s_D 45
这是代表团 - 与现实世界完全一样:
public interface Worker() {
public Result work();
}
public class Secretary() implements Worker {
public Result work() {
Result myResult = new Result();
return myResult;
}
}
public class Boss() implements Worker {
private Secretary secretary;
public Result work() {
return secretary.work();
}
}
Run Code Online (Sandbox Code Playgroud)
(添加了Worker接口以更接近Delegator模式)
aio*_*obe 19
如果您指的是委托模式,维基百科有一个很好的例子,用java编写.
我相信上面这个页面的较长的例子是最好的一个:
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()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27174 次 |
| 最近记录: |