设计模式(9)-结构型-装饰模式(Decorator)
2012-11-20 20:07
573 查看
概述
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。可以简称为"修修补补"适用性
1.在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。2.处理那些可以撤消的职责。
3.当不能采用生成子类的方法进行扩充时。
参与者
1.Component 定义一个对象接口,可以给这些对象动态地添加职责。2.ConcreteComponent 定义一个对象,可以给这个对象添加一些职责。
3.Decorator 维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。
4.ConcreteDecorator 向组件添加职责。
其基本类图如下图所示:
示例:
package com.sql9.structured; abstract class Component { public abstract void draw(); } class ConcreteComponent extends Component { private String name; public ConcreteComponent(String name) { this.name = name; } @Override public void draw() { System.out.println(String.format("ConcreteComponent - %s", name)); } } abstract class Decorator extends Component { protected Component internalComponent; public void setComponent(Component c) { this.internalComponent = c; } @Override public void draw() { if (internalComponent != null) { internalComponent.draw(); } } } class ConcreteDecorator extends Decorator { private String customName; public ConcreteDecorator(String name) { this.customName = name; } @Override public void draw() { extraDraw(); super.draw(); } protected void extraDraw() { System.out.println("Draw extra action in ConcreteDecorator..."); } } public class DecoratorTest { public static void main(String[] args) { ConcreteComponent c = new ConcreteComponent("This is the real component"); ConcreteDecorator d = new ConcreteDecorator("This is a decorator for the component"); d.setComponent(c); d.draw(); } }
结果:
Draw extra action in ConcreteDecorator...
ConcreteComponent - This is the real component
相关文章推荐
- Java经典设计模式-结构型模式-装饰模式(Decorator)
- 设计模式(八)装饰器模式Decorator(结构型)
- 面向对象设计模式之Decorator装饰模式(结构型)
- 设计模式(八)装饰器模式Decorator(结构型)
- 23种设计模式之装饰器模式(结构型,2 Decorator,c++实现)
- JAVA设计模式(7) —<结构型>装饰模式(Decorator)
- 【设计模式】结构型模式之装饰器Decorator
- 设计模式(四)装饰器模式Decorator(结构型)
- Java设计模式(9)——结构型模式之装饰模式(Decorator)
- 设计模式-结构型-装饰模式(Decorator)
- 设计模式(八)装饰器模式Decorator(结构型)
- 设计模式09: Decorator 装饰模式(结构型模式)
- Java设计模式之结构型模式-装饰器模式(Decorator)
- 设计模式之十四:Decorator(装饰)—对象结构型模式
- 结构型设计模式---Decorator模式(装饰模式)
- "围观"设计模式(13)--结构型之装饰模式(Decorator Pattern)
- C#设计模式之八装饰模式(Decorator Pattern)【结构型】
- 设计模式(3)-结构型-装饰模式(Decorator)
- 十二.结构型设计模式——Decorator Patten(装饰模式)
- 设计模式-结构型模式:装饰器模式 Decorator