複製鏈接
請複製以下鏈接發送給好友

委託模式

鎖定
委託模式(delegation pattern)軟件設計模式中的一項基本技巧。
中文名
委託模式
外文名
delegation pattern
性    質
軟件設計模式
學    科
計算機

委託模式簡介

在委託模式中,有兩個對象參與處理同一個請求,接受請求的對象將請求委託給另一個對象來處理。委託模式是一項基本技巧,許多其他的模式,如狀態模式策略模式訪問者模式本質上是在更特殊的場合採用了委託模式。委託模式使得我們可以用聚合來替代繼承,它還使我們可以模擬mixin [1] 

委託模式簡單的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()     } }
參考資料
  • 1.    Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1995). Design patterns : elements of reusable object-oriented software (14. print. ed.). Reading, Mass.: Addison-Wesley. p. 20. ISBN 0-201-63361-2.