设计模式.装饰者模式 Decorator
快速记忆
1. 类功能增强
2. 直接继承类(可以复写方法),然后传入需要增强的对象(构造方法),然后在用一个方法增强
3. 增加模板模式思想,在中间加以一层abstract,用来规范扩展的方法
定义
装饰者模式可以动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
开闭原则是对修改代码关闭,动态的扩展功能是允许的,装饰者并不修改目标类的代码。
场景
装饰,就是在原有的基础上装饰一些东西,专业的话就是功能的增强。
增加类功能方法还有其他几种,详细见附录
类图
实现
(完整代码见:com.haiwei.structure.decorator)
第一种:跟代理模式相同,只是侧重点不同public class Decorator1 implements Component { private Component component; public Decorator1(Component component) { this.component = component; } @Override public void operation() { System.out.println("before operation ... "); component.operation(); System.out.println("after operation ... "); }}第二种public abstract class AbstractDecorator implements Component { private Component component; public AbstractDecorator(Component component) { super(); this.component = component; } @Override public void operation() { beforeOperation(); component.operation(); afterOperation(); } public abstract void beforeOperation(); public abstract void afterOperation();}public class Decorator2 extends AbstractDecorator{ public Decorator2(Component component) { super(component); } @Override public void beforeOperation() { System.out.println("beforeOperation ..."); } @Override public void afterOperation() { System.out.println("afterOperation ..."); }}调用public class Client { public static void main(String[] args) { Component c11 = new ConcreteComponent(); c11.operation(); //1. 第一种方式 new Decorator1(new ConcreteComponent()).operation(); //2. 第二种方式 new Decorator2(new ConcreteComponent()).operation(); }}