结构型: 装饰器模式

扩展功能

装饰器模式(Decorator Pattern):动态给一个对象增加一些额外的职责。是一种替代继承的技术,使用对象之间的关联关系。

  1. 优点
    • 装饰模式比继承更灵活。
    • 可以动态扩展一个对象的功能,通过配置文件再运行时选择不同的具体装饰类。
    • 可以对一个对象进行多次装饰。
    • 具体构件类和具体装饰类可以独立变化,符合“开闭原则”。
  2. 缺点
    • 会产生很多小对象。
    • 装饰模式比继承更灵活但是也更加容易出错。
  3. 适用场景
    • 在不影响其他对象的情况下,动态、透明地给单个对象添加职责。
    • 在不能采用继承方式进行扩展时可以使用装饰模式。

1
2
3
public abstract class Component {
public abstract void operation();
}
1
2
3
4
5
6
public class ConcreteComponent extends Component {
@Override
public void operation() {
}
}
1
2
3
4
5
6
7
8
9
10
11
12
public abstract class Decorator extends Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class ConcreteDecoratorA extends Decorator {
private String additionState;
public ConcreteDecoratorA(Component component, String additionState) {
super(component);
this.additionState = additionState;
}
@Override
public void operation() {
super.operation();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
additionBehavior();
}
public void additionBehavior(){
}
}