委托模式

Demo1

  • 在委托模式中,有两个对象参与处理同一个请求,接受请求的对象将请求委托给另一个对象来处理。
  • 委托模式使得我们可以用聚合来替代继承。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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();
}
}

Demo2

  • 通过使用接口,委托可以做到类型安全并且更加灵活。
  • 委托的缺点是需要更多的代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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(); }
}
//类别C可以委托类别A或类别B,类别C拥有方法使自己可以在类别A或类别B间选择。
//因为类别A或类别B必须实现接口I规定的方法,所以在这里委托是类型安全的。
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()
}
}
0%