设计模式-装饰模式

装饰模式

指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。

就增加功能来说,装饰模式比生成子类更为灵活。

结构与实现

通常情况下,扩展一个类的功能会使用继承方式来实现。但继承具有静态特征,耦合度高,并且随着扩展功能的增多,子类会很膨胀。如果使用组合关

系来创建一个包装对象(即装饰对象)来包裹真实对象,并在保持真实对象的类结构不变的前提下,为其提供额外的功能,这就是装饰模式的目标。

组成

1
2
3
4
-   '抽象构件'(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
- '具体构件'(Concrete Component)角色:实现抽象构件,通过装饰角色为其添加一些职责。
- '抽象装饰'(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
- '具体装饰'(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

应用场景

1
2
3
-   当需要给一个'现有类添加附加职责',而又不能采用生成子类的方法进行扩充时。例如,该类被隐藏或者该类是终极类或者采用继承方式会产生大量的子类。
- 当需要通过对现有的一组基本功能进行排列组合而产生非常多的功能时,采用'继承关系很难实现',而采用装饰模式却很好实现。
- 当对象的'功能要求可以动态地添加,也可以再动态地撤销时'

实际中的应用

 Java I/O 标准库的设计。例如,

      (1) InputStream 的子类 FilterInputStream,

      (2) OutputStream 的子类 FilterOutputStream,

      (3) Reader 的子类BufferedReader 以及 FilterReader,

      (4) Writer 的子类 BufferedWriter、FilterWriter 以及 PrintWriter 等,

它们都是抽象装饰类。

实现

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
public class DecoratorPattern
{
public static void main(String[] args)
{
Component p=new ConcreteComponent();
p.operation();
System.out.println("---------------------------------");
Component d=new ConcreteDecorator(p);
d.operation();
}
}
//抽象构件角色
interface Component
{
public void operation();
}
//具体构件角色
class ConcreteComponent implements Component
{
public ConcreteComponent()
{
System.out.println("创建具体构件角色");
}
public void operation()
{
System.out.println("调用具体构件角色的方法operation()");
}
}
//抽象装饰角色
class Decorator implements Component
{
private Component component;
public Decorator(Component component)
{
this.component=component;
}
public void operation()
{
component.operation();
}
}
//具体装饰角色
class ConcreteDecorator extends Decorator
{
public ConcreteDecorator(Component component)
{
super(component);
}
public void operation()
{
super.operation();
addedFunction();
}
public void addedFunction()
{
System.out.println("为具体构件角色增加额外的功能addedFunction()");
}
}
文章目录
  1. 1. 装饰模式
    1. 1.1. 结构与实现
    2. 1.2. 组成
    3. 1.3. 应用场景
    4. 1.4. 实际中的应用
    5. 1.5. 实现
| 139.6k