The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.(有时候英文原版的比翻译过来更容易理解)
2.类图
Component类 定义对象接口,可以给这些动态地添加职责
ConcreteComponent类 定义具体的对象,Decorator类可以为其动态地添加职责
Decorator类
维护一个指向Component对象实例的引用,并实现了与其一样的接口
ConcreteDecorator类 定义了具体的装饰类,给内部的具体对象添加职责
3. 代码实现
3.1 Component类
abstract class Component{
//定义对象职责publicabstractvoidOperation();
}
3.2 ConcreteComponent类
publicclassConcreteComponentextendsComponent{@overridepublicvoidOperation(){
// do something
}
}
人靠衣装马靠鞍1.定义(官方的)装饰者模式可以动态地给一个对象增加其他职责。就扩展对象功能来说,装饰者模式比生成子类更为灵活。The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subcla