Fork me on GitHub

设计模式之一 装饰模式

装饰器(Decorator),其作用为特定对象提供拓展功能,是继承的一种替代方案,不用通过创建子类将其功能完善,对一特定对象,可以提供不同装饰对象,各个装饰器可以相互组合

装饰器有四个角色 Component 抽象接口,ConcreteComponent 具体实现,Decorator 装饰器接口,ConcreteDecorator 具体装饰器
Component:定义功能接口
ConcreteComponent: 实现Component接口
Decorator:装饰器,持有具体构件类ConcreteComponent的对象,是所有装饰的公共父类,它定义了所有装饰必须实现的方法,同时,它还保存了一个对于Component的引用,以便将用户的请求转发给Component,并可能在转发请求前后执行一些附加的动作。
ConcreteDecorator: 实现具体装饰功能

代码实例

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
//抽象接口
public interface Component {
void eat();
}
//具体实现类
public class ConcreteComponent implements Component {
@Override
public void eat() {
System.out.println("吃饭");
}
}
//装饰父类
public class Decorator implements Component {
private Component component;

public Decorator(Component component) {
this.component = component;
}

@Override
public void eat() {
component.eat();
}
}

//装饰类
public class ConcreteDecorator extends Decorator {


public ConcreteDecorator(Component component) {
super(component);
}


@Override
public void eat() {
// 可以在这里为其扩展功能
barbecue();
}

public void barbecue() {
System.out.println("和朋友一起吃烧烤");
}
}

//测试
public static void main(String[] args) {
Component component = new ConcreteComponent();
component.eat();
Decorator concreteDecorator = new ConcreteDecorator(component);
concreteDecorator.eat();
}
//测试结果
//吃饭
//和朋友一起吃烧烤

在Java中InputStream 大量使用装饰器模式,以BufferedInputStream为例
BufferedInputStream提供缓冲输入流功能,缓冲输入流相对于普通输入流的优势是,它提供了一个缓冲数组,每次调用read方法的时候,它首先尝试从缓冲区里读取数据,若读取失败(缓冲区无可读数据),则选择从物理数据源(譬如文件)读取新数据(这里会尝试尽可能读取多的字节)放入到缓冲区中,最后再将缓冲区中的内容部分或全部返回给用户

以下为创建BufferedInputStream方法

1
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(""));

下图为BufferedInputStream类图
InputStream

通过类图与代码可以分析,在使用BufferedInputStream中,InputStream为抽象接口,FileInputStream为具体实现类,FilterInputStream为装饰器父类
BufferedInputStream为具体装饰类

显示 Gitment 评论