一.简介
装饰(Decorator)模式在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能) 。
模式的结构
1.抽象构件(Component):抽象接口以规范准备接收附加责任的对象。
2.具体构件(Concrete Component):实现抽象构件,通过装饰角色为其添加一些职责。
3.抽象装饰(Decorator):继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
4.具体装饰(ConcreteDecorator):实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。
二.实现
package com.vincent;
/**
* 抽象构件
*/
interface Component{
}
/**
* 抽象构建的实现
*/
class ComponentImpl implements Component{
}
/**
* 抽象装饰器
*/
abstract class AbsDecoratorComponent implements Component{
protected Component component;
}
/**
* 具体装饰器
*/
class DecoratorComponent extends AbsDecoratorComponent{
public DecoratorComponent(Component component) {
this.component = component;
}
}
三.总结
1.相比采用继承增加额外功能带来的耦合性、类爆炸,装饰设计在不改变原有类的情况下增加功能
2.java IO的BufferedInputStream、BufferedReader 等就是装饰设计模式的经典体现