委託模式(delegation pattern)是軟體設計模式中的一項基本技巧。
基本介紹
- 中文名:委託模式
- 外文名:delegation pattern
- 性質:軟體設計模式
- 學科:計算機
簡介
簡單的Java例子
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例子
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() } }