课程表

设计模式课程

工具箱
速查手册

委托模式

当前位置:免费教程 » Java相关 » 设计模式

委托模式是软件设计模式中的一项基本技巧。在委托模式中,有两个对象参与处理同一个请求,接受请求的对象将请求委托给另一个对象来处理。委托模式是一项基本技巧,许多其他的模式,如状态模式、策略模式、访问者模式本质上是在更特殊的场合采用了委托模式。委托模式使得我们可以用聚合来替代继承,它还使我们可以模拟mixin。

简单的Java例子

在这个例子里,类模拟打印机Printer拥有针式打印机RealPrinter的实例,Printer拥有的方法print()将处理转交给RealPrinter的方法print()。

  1. class RealPrinter { // the "delegate"
  2. void print() {
  3. System.out.print("something");
  4. }
  5. }
  6. class Printer { // the "delegator"
  7. RealPrinter p = new RealPrinter(); // create the delegate
  8. void print() {
  9. p.print(); // delegation
  10. }
  11. }
  12. public class Main {
  13. // to the outside world it looks like Printer actually prints.
  14. public static void main(String[] args) {
  15. Printer printer = new Printer();
  16. printer.print();
  17. }
  18. }

复杂的Java例子

通过使用接口,委托可以做到类型安全并且更加灵活。在这个例子里,类别C可以委托类别A或类别B,类别C拥有方法使自己可以在类别A或类别B间选择。因为类别A或类别B必须实现接口I规定的方法,所以在这里委托是类型安全的。这个例子显示出委托的缺点是需要更多的代码。

  1. interface I {
  2. void f();
  3. void g();
  4. }
  5. class A implements I {
  6. public void f() { System.out.println("A: doing f()"); }
  7. public void g() { System.out.println("A: doing g()"); }
  8. }
  9. class B implements I {
  10. public void f() { System.out.println("B: doing f()"); }
  11. public void g() { System.out.println("B: doing g()"); }
  12. }
  13. class C implements I {
  14. // delegation
  15. I i = new A();
  16. public void f() { i.f(); }
  17. public void g() { i.g(); }
  18. // normal attributes
  19. public void toA() { i = new A(); }
  20. public void toB() { i = new B(); }
  21. }
  22. public class Main {
  23. public static void main(String[] args) {
  24. C c = new C();
  25. c.f(); // output: A: doing f()
  26. c.g(); // output: A: doing g()
  27. c.toB();
  28. c.f(); // output: B: doing f()
  29. c.g(); // output: B: doing g()
  30. }
  31. }
本节内容来源:https://zh.wikipedia.org/wiki/%E5%A7%94%E6%89%98%E6%A8%A1%E5%BC%8F
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号