设计模式之委派模式

3,246 阅读1分钟

总结

在委派模式(Delegate)中,有两个或多个对象参与处理同一个请求,接受请求的对象将请求委派给其他对象来处理。

比如priter对象接受打印请求,然后他可以将打印请求委派给彩色打印机、黑白打印机等其他对象处理。

简单例子

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

class RealPrinter { 
    void print() { 
      System.out.print("something"); 
    }
}
 
class Printer { 
    RealPrinter p = new RealPrinter(); // create the delegate 
    void print() { 
      p.print(); // delegation
    } 
}
 
public class Main {
    // 对外来说,就像printer类的实例在打印一样
    public static void main(String[] args) {
        Printer printer = new Printer();
        printer.print();
    }
}

复杂的例子

通过使用接口,委派可以做到类型安全并且更加灵活。在这个例子里,类别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()
    }
}

可以使用反射,当添加被委派者的时候,无需添加委派代码

参考

Java的委派模式代码实例讲解 | 红黑联盟