“动态的将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的扩展方案”。
**
1. 我们用个例子来说明下
我们想要一杯深培咖啡(被装饰对象,Component),这个咖啡需要加入摩卡(装饰者,Decorator)和奶泡(装饰者,Decorator)。加入不同的元素我们需要计算价格(Component Operation)。
有一个煎饼摊,人们去买煎饼(被装饰对象,Component,有些人要加火腿(装饰者,Decorator的,有些人要加鸡蛋(装饰者,Decorator的,有些人要加生菜(装饰者,Decorator的,或者全加。加了不同的材料,就有不同的烹饪方式(Component Operation)。
2. 实现
- Component
定义可以动态添加任务的对象的接口
abstract class Component {public abstract void operation();}
- ConcreteComponent
定义一个要被装饰器装饰的对象
class ConcreteComponent extends Component {public void operation(){System.out.println("ConcreteComponent say");}}
- Decorator
维护对组件对象和其子类组件的引用
abstract class Decorator extends Component {protected Component component;public Decorator(Component component) {this.component = component;}public void operation(){component.operation();}}
- ConcreteDecorator
向组件添加新的职责
class ConcreteDecoratorA extends Decorator {public ConcreteDecoratorA(Component component){super(component);}private void operationFirst(){System.out.println("operationFirst say");}private void operationLast(){System.out.println("operationLast say");}public void operation() {operationFirst();super.operation();operationLast();}//新功能public void anotherOperation() {System.out.println("another operation");}}
3. 优缺点
优点
装饰器模式在jdk中的使用:java.io类
