设计模式之装饰者模式
来源:互联网 发布:stc单片机程序烧录 编辑:程序博客网 时间:2024/06/14 11:44
什么是装饰者模式
装饰者模式动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。这就是面向对象设计中常提到的优先使用组合而不是继承。
UML图
图中抽象类Component是被装饰者基类,ConcreteComponent是将要动态地加上新行为的对象,它扩展了Component。Decorator是装饰者共同实现的接口或者是抽象类。ConcreteDecoratorA和ConcreteDecoratorB都是实现或扩展了Decorator的装饰者,它们都有一个Component的私有实例变量,实现了抽象类的方法,并且可以加上新的方法从而实现扩展功能。
代码实现
Component
/** * Created by yrs on 2017/7/2. */public abstract class Component { public abstract void say();}
ConcreteComponent
/** * Created by yrs on 2017/7/2. */public class ConcreteComponent extends Component { @Override public void say() { System.out.println("this is ConcreteComponent."); }}
Decorator
/** * Created by yrs on 2017/7/2. */public abstract class Decorator extends Component {}
ConcreteDecoratorA
/** * Created by yrs on 2017/7/2. */public class ConcreteDecoratorA extends Decorator { private Component component; public ConcreteDecoratorA(Component component) { this.component = component; } @Override public void say() { preSay(); component.say(); sufSay(); } public void preSay() { System.out.println("Welcome everyone!"); } public void sufSay() { System.out.println("Thank you!"); }}
ConcreteDecoratorB
/** * Created by yrs on 2017/7/2. */public class ConcreteDecoratorB extends Decorator { private Component component; public ConcreteDecoratorB(Component component) { this.component = component; } @Override public void say() { component.say(); sayHelp(); } public void sayHelp() { System.out.println("please help me!"); }}
Test
/** * Created by yrs on 2017/7/2. */public class Test { public static void main(String [] args) { //用ConcreteDecoratorA类装饰ConcreteComponent对象 component = new ConcreteDecoratorA(component); //用ConcreteDecoratorB类装饰ConcreteComponent对象 component = new ConcreteDecoratorB(component); component.say(); }}
装饰者模式的重点是装饰者有一个被装饰者的实例变量
Java IO中的装饰者模式
代码下载:https://github.com/ByrsH/Design-Patterns/tree/master/Design%20Patterns/src/main/java/com/yrs/decorator
阅读全文
1 0
- 设计模式之装饰者设计模式
- 设计模式 之 装饰者
- 设计模式之装饰者模式
- 设计模式之装饰者模式
- 设计模式之Decorator(装饰者模式)
- 设计模式之五---装饰者模式
- 设计模式之---装饰者模式
- c++设计模式之装饰者模式
- Php设计模式之装饰者模式
- java设计模式之装饰者模式
- 设计模式之装饰者模式
- 【设计模式】之装饰者模式
- HeadFirst设计模式之装饰者模式
- c++设计模式之装饰者模式
- 设计模式之装饰者模式
- 设计模式之--装饰者模式
- 设计模式之装饰者模式
- 设计模式之装饰者模式
- Java抽象类与接口
- 二叉树的镜像
- IntelliJ IDEA:Unregistered VCS root detected. The directory…is under Git, but is not registered in t
- websphere mq java base classes
- 编译原理三大经典书籍(龙书 虎书 鲸书)
- 设计模式之装饰者模式
- HDU4734 F(x)
- scala(2)-----基础语法
- -----暴力dfs+回溯 hdu 1045-Fire Net
- SQL的四种连接-左外连接、右外连接、内连接、全连接
- POJ3093 浅谈背包DP预处理
- 判定字符串形式IP是否有效
- 替换空格
- [牛客网,剑指offer,python] 重建二叉树