装饰模式(decorator pattern)是一种比较常见的模式。
定义:
装饰模式类图如下所示。
装饰模式有以下4个角色。
component.java
public interface component { public void operation(); }
concretecomponent.java
public class concretecomponent implements component { @override public void operation() { system.out.println("业务代码"); } }
decorator.java
public abstract class decorator implements component { private component component = null; public decorator(component component) { this.component = component; } @override public void operation() { this.component.operation(); } }
concretedecorator.java
public class concretedecorator extends decorator { public concretedecorator(component component) { super(component); } // 定义自己的方法 public void selfmethod() { system.out.println("修饰"); } // 重写operation @override public void operation() { this.selfmethod(); super.operation(); } }
client.java
public class client { public static void main(string[] args) { component component = new concretecomponent(); // 进行装饰 component = new concretedecorator(component); component.operation(); } }
优点:
缺点:
应用场景:
装饰模式是对继承的有力补充。单纯使用继承时,在一些情况下就会增加很多子类,而且灵活性较差,维护也不容易。装饰模式可以替代继承,解决类膨胀的问题,如java基础类库中的输入输出流相关的类大量使用了装饰模式。
摘自:
青岛东合信息技术有限公司 . 设计模式(java版) . 电子工业出版社,2012,78-80.
如对本文有疑问, 点击进行留言回复!!
软件设计模式六大原则-接口隔离原则 Interface Segregation Principle
设计模式之解释器模式(附:SpelExpressionParser中解释器模式应用分析)
网友评论