委托模式( delegate)

来源:互联网 发布:上海音乐学院网络报名 编辑:程序博客网 时间:2024/06/06 08:08

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

[编辑]简单的Java例子

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

  class RealPrinter { // the "delegate"     void print() {        System.out.print("something");      } }  class Printer { // the "delegator"     RealPrinter p = new RealPrinter(); // create the delegate      void print() {        p.print(); // delegation     }  }  public class Main {     // to the outside world it looks like Printer actually prints.     public static void main(String[] args) {         Printer printer = new Printer();         printer.print();     } }

[编辑]复杂的Java例子

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

  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     public void toA() { i = new A(); }     public 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()     } }

[编辑]参考

参见软件设计模式和后对象程序设计。



转载地址:http://zh.wikipedia.org/wiki/%E5%A7%94%E6%89%98%E6%A8%A1%E5%BC%8F


应用实例:


在程序开发当中很多时候都会遇上不同的方法中有相同的业务逻辑代码,这个时候我们应该想办法把相同业务逻辑代码抽取出来,封装一下。当遇到下面的这种情况下时,我们可以考虑使用delegate 设计模式来封装代码。


///  /// 一些函数含有部分重复代码 /// void OriginalA(){DoThingsA();// unique codeDoThingsB();}///  /// 另外一个含有部分重复代码的函数 /// void OriginalB(){DoThingsA();// 没有重复的代码DoThingsB();}

现在我们重构含有部分相同代码的函数,用delegate模式重写它们:

///  /// Encapsulate shared functionality /// /// User defined actionvoid UniqueWrapper(Action action){DoThingsA();action();DoThingsB();}///  /// New implmentation of A /// void NewA(){UniqueWrapper(() =>{// unique code});}///  /// New implementation of B /// void NewB(){UniqueWrapper(() =>{// unique code});}



原创粉丝点击