GOF 结构型模式 系列文章
1. 概述
-
功能作用
- 动态的为一个对象增加新的功能。
- 装饰模式是一种用于代替继承的技术,无须通过继承增加子类就能扩展对象的新功能,可以动态的增加或删除对象的职责。
- 使用对象的关联关系代替继承关系,更加灵活,同时避免类型体系的快速膨胀,降低系统的耦合度。使得需要装饰的具体构建类和具体装饰类可以独立变化,以便增加新的具体构建类和具体装饰类。
-
优点
- 扩展对象功能,比继承灵活,不会导致类个数急剧增加
- 可以对一个对象进行多次装饰,创造出不同行为的组合,得到功能更加强大的对象
- 具体构建类和具体装饰类可以独立变化,用户可以根据需要自己增加
- 新的具体构件子类和具体装饰子类。
-
缺点
- 产生很多小对象。大量小对象占据内存,一定程度上影响性能。
- 装饰模式易于出错,调试排查比较麻烦。
-
模式的结构
- 抽象构件(
Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。 - 具体构件(
ConcreteComponent)角色:实现抽象构件,通过装饰角色为其添加一些职责。 - 抽象装饰(
Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。 - 具体装饰(
ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

- 抽象构件(
2. 实例
public class DecoratorTest {
public static void main(String[] args) {
Decorator2 decorator2 = new Decorator2(new Decorator1(new Car()));
decorator2.operation();
}
}
//抽象构件角色
interface ICar {
public void operation();
}
//具体构件角色
class Car implements ICar {
public Car() { System.out.println("new Car"); }
public void operation() { System.out.println(this.getClass() + "::operation()"); }
}
//抽象装饰角色
class AbstractDecorator implements ICar {
private ICar iCar;
public AbstractDecorator(ICar iCar) { this.iCar = iCar; }
public void operation() { iCar.operation(); }
}
//具体装饰角色1
class Decorator1 extends AbstractDecorator {
public Decorator1(ICar iCar) { super(iCar); }
public void operation() {
super.operation();
addedFunction();
}
public void addedFunction() { System.out.println(this.getClass() + "::addedFunction()"); }
}
//具体装饰角色2
class Decorator2 extends AbstractDecorator {
public Decorator2(ICar iCar) { super(iCar); }
public void operation() {
super.operation();
addedFunction();
}
public void addedFunction() { System.out.println(this.getClass() + "::addedFunction()"); }
}
测试结果如下

3. 装饰器模式的扩展
- 如果只有一个具体构件而没有抽象构件时,可以让抽象装饰继承具体构件
- 如果只有一个具体装饰时,可以将抽象装饰和具体装饰合并
255

被折叠的 条评论
为什么被折叠?



