定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。
主要优点有:
- 采用装饰模式扩展对象的功能比采用继承方式更加灵活。
- 可以设计出多个不同的具体装饰类,创造出多个不同行为的组合。
主要缺点是:装饰模式增加了许多子类,如果过度使用会使程序变得很复杂。
图示如下:
Component接口:定义装饰物执行的公共操作;
ConcreteComponent类:实现Component接口;
Decorator抽象类:是所有装饰类的基类,里面包含的成员变量component指向了被装饰的对象。该类也实现了Component接口;
ConcreteDecorator类:具体装饰类,添加功能,可以有很多个。
举例:
Component接口:
public interface IceCream {
// Component接口
public void AddTopping();
}
ConcreteComponent类:
public class PlainIceCream implements IceCream {
// ConcreteComponent(基础实现,无填加的冰激凌)
@Override
public void AddTopping() {
System.out.println("Plain IceCream ready for so