委派模式
在委派模式中,有两个对象参与处理同一个请求,接受请求的对象将请求委派给另一个对象来处理。委派模式使得我们可以用聚合来替代继承
使用委派模式的场景
- 一个接口已知有多重实现,但对客户端屏蔽实现细节
- 差异化逻辑委派给其他类实现,通过组合形式进行解耦
public interface Printer {
void print(final String message);
}
public class HpPrinter implements Printer {
@Override
public void print(final String message) {
System.out.println("HP Printer : " + message);
}
}
public class EpsonPrinter implements Printer {
@Override
public void print(final String message) {
System.out.println("Epson Printer : " + message);
}
}
public class PrinterController implements Printer {
private final Printer delegate;
public PrinterController(final Printer delegate) {
this.delegate = delegate;
}
@Override
public void print(final String message) {
delegate.print(message);
}
}
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
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
测试类
public class PrinterApp {
public static void main(String[] args) {
PrinterController controller = new PrinterController(new HpPrinter());
controller.print("hello world");
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
Last Updated: 2024/04/23, 01:30:37