版權(quán)歸原作者所有,如有侵權(quán),請聯(lián)系我們

[科普中國]-委托模式

科學(xué)百科
原創(chuàng)
科學(xué)百科為用戶提供權(quán)威科普內(nèi)容,打造知識科普陣地
收藏

**委托模式(delegation pattern)**是軟件設(shè)計模式中的一項基本技巧。

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

簡單的Java例子在這個例子里,類模擬打印機(jī)Printer擁有針式打印機(jī)RealPrinter的實例,Printer擁有的方法print()將處理轉(zhuǎn)交給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(); } }復(fù)雜的Java例子通過使用接口,委托可以做到類型安全并且更加靈活。在這個例子里,類別C可以委托類別A或類別B,類別C擁有方法使自己可以在類別A或類別B間選擇。因為類別A或類別B必須實現(xiàn)接口I規(guī)定的方法,所以在這里委托是類型安全的。這個例子顯示出委托的缺點(diǎn)是需要更多的代碼。

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() } }本詞條內(nèi)容貢獻(xiàn)者為:

黃倫先 - 副教授 - 西南大學(xué)