装饰器模式理论

装饰器模式相对于简单的组合关系,还有两个比较特殊的地方。

1、装饰器类和原始类继承同样的父类,这样我们可以对原始类“嵌套”多个装饰器类。

比如下面这种,他就是对DataInputStream的一种增强,装进了一个FileInputStream和BufferedInputStream

1
2
3
4
InputStream in = new FileInputStream("/user/wangzheng/test.txt");
InputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);
int data = din.readInt();

2、装饰器类是对功能的增强,这也是装饰器模式应用场景的一个重 要特点。

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
// 代理模式的代码结构(下面的接口也可以替换成抽象类)
public interface IA {
void f();
}
public class A impelements IA {
public void f() {
//...
}
}

// 代理类,在原先的类A的f操作上添加一些其他的功能(不改变原先的A)
public class AProxy impements IA {
private IA a;
public AProxy(IA a) {
this.a = a;
}
public void f() {
// 新添加的代理逻辑
a.f();
// 新添加的代理逻辑
}
}

// 装饰器模式的代码结构(下面的接口也可以替换成抽象类)
public interface IA {
void f();
}
public class A impelements IA {
public void f() {
//...
}
}
public class ADecorator impements IA {
private IA a;
public ADecorator(IA a) {
this.a = a;
}
public void f() {
// 功能增强代码
a.f();
// 功能增强代码
}
}

参考

《设计模式之美》