lusiqi

设计模式-装饰模式,介绍装饰模式,及代码实现。


简介

装饰模式是结构型设计模式,动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

角色

  • 组件抽象类:组件的抽象类,描述简单职责
  • 组件实现类:抽象类的实现类,即被修饰的对象
  • 组件装饰类:装饰类继承组件抽象父类,装饰子类继承装饰父类,不同装饰子类在前一个修饰的基础上继续完成修饰。

实现说明

以人搭配穿衣服为例:人为组件抽象类Component,小明为组件实现类ConcreteComponent,服饰为组件装饰类Decorator,具体的服饰类型为装饰子类,装饰模式是为已有功能动态的添加功能的一种方式。

当系统需要新功能的时候,是像旧的类里面添加新的代码,这些新的代码通常装饰了原有类的核心职责或主要行为,比如穿西装或者嘻哈装,在主类服饰中增加了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度。

代码实现

组件抽象类

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @description Component是定义一个对象抽象类,可以给这些对象动态地添加职责
* @author dxy
* @date 20200309
*/
public abstract class Component {

/**
* 操作方法
*/
public abstract void operation();
}

组件实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @description ConcreteComponent是定义一个具体的对象,也可以给这个对象添加一些职责
* @author dxy
* @date 20200309
*/
public class ConcreteComponent extends Component {

@Override
public void operation() {
System.out.println("具体对象的操作");
}

}

装饰类

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
/**
* @description Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,
* 但对于Component来说,是无需知道Decorator的存在的
* @author dxy
* @date 20200309
*/
public abstract class Decorator extends Component {
protected Component component;

public Component getComponent() {
return component;
}

public void setComponent(Component component) {
this.component = component;
}

@Override
public void operation() {
if (component != null) {
component.operation();
}
}

}

class ConcreteDecoratorA extends Decorator {
private String addedState;

@Override
public void operation() {
// 首先运行原Component的operation(),再执行本类的功能,如addedState,相当于对原Component进行了装饰
super.operation();
addedState = "A中的new state ";
System.out.println(addedState + "具体装饰对象A的操作");
}
}

class ConcreteDecoratorB extends Decorator {
@Override
public void operation() {
super.operation();
addedBehavior();
System.out.println("具体装饰对象B的操作");
}

public void addedBehavior() {
System.out.print("B中的新增行为 ");
}
}

class ConcreteDecoratorC extends Decorator {
@Override
public void operation() {
super.operation();
System.out.println("C没有特殊行为 " + "具体装饰对象C的操作");
}

}

客户端调用类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @description 装饰模式客户端调用代码,装饰的过程更像是层层包装,用前面的对象装饰后面的对象
* @author dxy
* @date 20200309
*/
public class DecoratorClient {

public static void main(String[] args) {

ConcreteComponent concreteComponent = new ConcreteComponent();
ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA();
ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB();
ConcreteDecoratorC concreteDecoratorC = new ConcreteDecoratorC();

concreteDecoratorA.setComponent(concreteComponent);
concreteDecoratorB.setComponent(concreteDecoratorA);
concreteDecoratorC.setComponent(concreteDecoratorB);
concreteDecoratorC.operation();

}
}

输出结果:

1
2
3
4
具体对象的操作
A中的new state 具体装饰对象A的操作
B中的新增行为 具体装饰对象B的操作
C没有特殊行为 具体装饰对象C的操作

 评论