装饰模式又名包装(Wrapper)模式
装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代的方案。
装饰模式以对客户端透明的方式动态的给一个对象附加上更多的责任。换言之,客户端并不会感觉对象在装饰前和装饰后有什么不同。
装饰模式可以在不创造更多的子类的情况下,将对象的功能加以扩展。(继承也可以实现,但是继承是静态的关系,而装饰模式对象具有多少功能取决于怎么用,是动态的关系)。
装饰模式把客户端的调用委派到被装饰类。装饰模式的关键在于这种扩展完全是透明的。
装饰模式是在不必改变原来类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
装饰模式的角色:
抽象构件角色(Component):给出一个抽象接口,以规范准备接受附加责任的对象。
具体的构件角色(Concrete Component):定义一个将要接受附加责任的类。
装饰角色(Decorator):持有一个构件(Component)对象的引用,并定于一个与抽象构件接口一致的接口。
具体装饰角色(Concrete Decorator):负责给构件对象“贴上”附加的责任。
装饰模式的特点:
装饰对象和真实的对象有相同接口。这样客户端对象就可以以和真实对象相同的方式和装饰对象交互。
装饰对象包含一个真实对象的引用(Reference)
装饰对象接受到所有来自客户端的请求。它把这些请求转发给真实的对象。
装饰对象可以在转发这些请求以前或者以后增加一些附加的功能(类似于代理模式)。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能的扩展。
装饰模式 vs 继承
装饰模式:
用来扩展特定对象的功能
不需要子类
动态
运行时分配职责
防止由于子类而导致的负责和混乱
更多的灵活性
对于一个给定的对象,同时可能有不同的装饰对象,客户端可以通过它的需要选择合适的装饰对象发送消息。
继承:
用来扩展一类的对象的功能
需要子类
静态
编译时分派职责
导致很多的子类产生
缺乏灵活性
大家可以像一下,如果java io流不常用装饰模式,那么java io中类的数量将会大大的变多,就更加的不容易掌握了。
类比:
DataOutputStream out = new DataOutputStram (new BufferedOutputStream (new FileOutputStream ("1.txt")));
这个是java中使用装饰模式的例子。
java io流在就采用了装饰模式。
OutputStream 就相当于Component
FileOutputStream 就相当于Concrete Component
FilterOutputStream 就相当于Decorator
BufferedOutputStream 就相当于Concrete Decorator
实现自己简单的装饰模式:
例子:
public interface Component { public void doSomething (); } public class ConcreteComponent implements Component{ @Override public void doSomething() { System.out.println("功能A"); } } public class Decorator implements Component{ private Component component; public Decorator (Component component) { this.component = component; } @Override public void doSomething() { this.component.doSomething(); } } public class ConcreteDecorator_1 extends Decorator{ public ConcreteDecorator_1(Component component) { super(component); } @Override public void doSomething() { super.doSomething(); this.doAnotherThing(); } private void doAnotherThing () { System.out.println("功能B"); } } public class ConcreteDecorator_2 extends Decorator { public ConcreteDecorator_2(Component component) { super(component); } @Override public void doSomething() { // TODO Auto-generated method stub super.doSomething(); this.doAnothing(); } private void doAnothing () { System.out.println("功能C"); } } public class TestDe { public static void main(String[] args) { //节点流 Component component = new ConcreteComponent (); //过滤流 Component component2 = new ConcreteDecorator_1 (component); //过滤流 Component component3 = new ConcreteDecorator_2 (component2); component3.doSomething(); } }