【设计模式】装饰模式
2016-12-16 12:14
267 查看
1. 定义:
表示动态的给一个对象添加一些新的功能,但是比生成子类方式更灵活。(当然利用子类继承父类也可以实现,但是不推荐)核心:动态地扩展一个实现类的功能。(装饰模式是继承关系的一个替换方案,不管装饰多少层,返回的对象构件角色)
2. 角色:
抽象构件(Component)角色:定义一个对象接口,可以给这些对象动态添加职责。具体构件(ConcreteComponent)角色:是定义了一个具体的对象(例如:车),也可以给这个对象添加一些其他职责。
装饰(Decorator)角色:装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对Component来说,是无需知道Decorator存在的。
具体装饰(ConcreteDecorator)角色:就是具体的装饰对象了(飞车,水车..),它起到了给Component添加职责的功能。
以Java IO流中的设计为例:
抽象构件角色——Input/OutputStream
具体构件角色——FileInput/OutputStream
装饰构件角色——FilterInput/OutputStream
具体装饰角色——BufferedInput/OutputStream,DataInput/OutputStream
接口Component,定义了基本职责
package DecoratorPattem; /** * InputStream * @author Administrator * */ public interface Component { public void doThingA(); }
类ConcreteComponent,实现了Component中的功能
package DecoratorPattem; public class ConcreteComponent implements Component{ /** * FileInputStream * @param args */ @Override public void doThingA(){ System.out.println("Do A thing"); } }
类Decorator,是ConcreteComponent的具体实现类
package DecoratorPattem; /** * FilterInputStream * @author Administrator * */ public class Decorator implements Component { private Component component=null; public Decorator(Component component){ this.component=component; } @Override public void doThingA() { component.doThingA();//调用被装饰对象的方法 } }
类ConcreteDecorator,对类Decorator做功能上的装饰。
package DecoratorPattem; /* * BufferedInputStream */ public class ConcreteDecorator1 extends Decorator { public ConcreteDecorator1(Component component) { super(component); } @Override public void doThingA() { super.doThingA();//调用被包装类的方法 doThingB(); } //扩展功能 private void doThingB(){ System.out.println("Do B thing"); } }
package DecoratorPattem; public class ConcreteDecorator2 extends Decorator { public ConcreteDecorator2(Component component) { super(component); } @Override public void doThingA() { super.doThingA();//调用被包装类的方法 doThingC(); } //扩展功能 private void doThingC(){ System.out.println("Do C thing"); } }
相关文章推荐
- 设计模式---装饰模式
- NET设计模式之一:装饰模式(Decorator Pattern)
- 设计模式中结构型模式(四)装饰模式(Decorator)
- 设计模式c#描述——装饰(Decorator)模式
- 第四个设计模式:装饰模式
- 设计模式c#语言描述——装饰(Decorator)模式
- 结构型设计模式---Decorator模式(装饰模式)
- .NET设计模式研究之装饰模式
- 解读设计模式----装饰模式(Decorator Pattern)
- 乐在其中设计模式(C#) - 装饰模式(Decorator Pattern)
- 用实例解说Dot Net设计模式——装饰模式
- 第四个设计模式:装饰模式
- AspectJ实现设计模式(七)—装饰模式
- 乐在其中设计模式(C#) - 装饰模式(Decorator Pattern)
- 设计模式之---装饰(decorator)
- 设计模式c#语言描述——装饰(Decorator)模式
- 设计模式之装饰模式篇(Decorator)
- 设计模式之--装饰器模式的硬编码的静态装饰和链化
- 设计模式学习笔记-装饰模式
- 设计模式(11)-装饰模式(Decorator)