Decorator Pattern

Decorator Pattern

  1. 装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案
  2. 装饰模式以对客户透明的方式动态的给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。
  3. 装饰模式可以在不创造更多子类的情况下将对象的功能加以扩展。
  4. 装饰模式把客户端的调用委派到被装饰类。装饰模式的关键在于这种扩展完全是透明的。
  5. 装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过传建一个包装对象,月就是装饰来包裹真实的对象。
  6. 装饰模式的角色:
  • 抽象构件角色(Component):给出一个抽象接口,以规范准备接收附加责任的对象。
  • 具体构件角色(Concrete Component):定义一个将要接收附加责任类的类。
  • 装饰角色(Decorator):持有一个构建(Component)对象的引用,并定义一个与抽象构建接口一致的接口
  • 具体装饰角色(Concrete Decorator):负责给构建对象“贴上”附加的责任。
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public interface Component {
public void doSomething();
}
public class ConcreteComponent implements Component {
@Override
public void doSomething() {
System.out.println("功能A");
}
}
public class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void doSomething() {
this.component.doSomething();
}
}
public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component component) {
super(component);
}
@Override
public void doSomething() {
super.doSomething();
doAnotherthing();
}
public void doAnotherthing() {
System.out.println("功能B");
}
}
public class ConcreteDecorator2 extends Decorator {
public ConcreteDecorator2(Component component) {
super(component);
}
@Override
public void doSomething() {
super.doSomething();
doAnotherthing();
}
public void doAnotherthing() {
System.out.println("功能C");
}
}
public class Client {
public static void main(String[] args) {
//节点流
Component component = new ConcreteComponent();
//过滤流
Component component1 = new ConcreteDecorator1(component);
//过滤流
Component component2 = new ConcreteDecorator2(component1);
component2.doSomething();
}
}