描述
- 定义:动态地给一个对象添加一些额外的职责,就增加功能来说装饰模式比生产子类更加灵活
- 角色:组件Component、具体组件ConcreteComponent(被装饰者)、装饰者Decorator、具体装饰者ConcreteDecorator
类图
代码
public interface Component {
void operate();
}
public class ConcreteComponent implements Component{
@Override
public void operate(){
//do
}
}
public class Decorator implements Component{
private Component component;
public Decorator(Component component){
this.component=component;
}
@Override
public void operate(){
//do
}
}
public class ConcreteDecorator1 implements Decorator{
public ConcreteDecorator1(Component component){
super(component);
}
@Override
public void operate(){
//do
super.operate();
}
}
public class ConcreteDecorator2 implements Decorator{
public ConcreteDecorator1(Component component){
super(component);
}
@Override
public void operate(){
//do
super.operate();
}
}
public class Main{
public static void main(String[] args){
Component component=new ConcreteComponent();
component=new ConcreteDecorator1(comopnent);
component=new ConcreteDecorator2(comopnent);
component.operate();
}
}
说明
- 装饰模式是对继承的补充,不能完全代替继承
- 装饰类相互独立,方法执行顺序可以任意组合
优势
- 装饰类和被装饰类不会相互耦合
- 装饰模式的继承关系的一个替代方案
- 装饰模式可以动态扩展一个实现类的功能
劣势
场景
- 扩展一个类的功能
- 动态地给对象增加功能
- 对兄弟类进行改装或增加功能
应用
- I、Java I/0
- Component:InputStream
- ConcreteComponent:ByteArrayInputStream/FileInputStream/PipedInputStream/StringBufferInputStream
- Decorator:FilterInputStream
- ConcreteDecorator:BufferedInputStream/DataInputStream/PushbackInputStream/LineNumberInput
- II、ServletRequestWrapper、HttpServletRequestWrapper对ServletRequest的封装
实践