概述
- 装饰模式可以在不改变一个对象本身功能的基础上给对象增加额外的新行为; 装饰模式是一种用于替代继承的技术,它通过一种无须定义子类的方式来给对象动态增加职责,使用对象之间的组合关系取代类之间的继承关系。在装饰模式中引入了装饰类,在装饰类中既可以调用待装饰的原有类的方法,还可以增加新的方法,以扩充原有类的功能。
- 定义:动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活。
- 装饰模式是一种对象结构型模式。
- 学习难度:★★★☆☆
- 使用频率:★★★☆☆
优缺点
- 优点
- 解耦装饰者和被装饰者
- 是继承的一种替代方式,实现的还是is-a关系
- 装饰者可以方便扩展具体装饰者类
- 缺点
类图

组成角色
- 抽象构件(Component)
- 具体构件(ConcreteComponent)
- 装饰角色(Decorator)
- 具体装饰角色(ConcreteDecorator)
Code Example
抽象构件(Component)
public interface Component {
public void operation();
}
具体构件(ConcreteComponent)
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("具体对象的操作!");
}
}
装饰角色(Decorator)
聚合Component
聚合具体构建接口、并调用接口方法,保持原有的功能
集成抽象装饰者,super父方法的同时增加额外的职责方法
public class Decorator implements Component {
private Component component;
@Override
public void operation() {
if (null != component) {
component.operation();
}
}
public void setComponent(Component component) {
this.component = component;
}
}
具体装饰角色(ConcreteDecorator)
public class ConcreteDecoratorA extends Decorator {
@Override
public void operation() {
super.operation();
addState();
System.out.println("具体装饰对象A的操作!");
}
private void addState() {
System.out.println("add new state");
}
}
public class ConcreteDecoratorB extends Decorator {
private String state;
@Override
public void operation() {
super.operation();
state = "new state";
System.out.println("具体装饰对象B的操作:" + state);
}
}
客户端
public class DecoratorPattern {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Decorator decoratorA = new ConcreteDecoratorA();
Decorator decoratorB = new ConcreteDecoratorB();
component.operation();
decoratorA.operation();
decoratorB.operation();
}
}