装饰模式的类图如下:
菱形表示关联关系,可以理解为车轮与汽车的关联关系
在装饰模式中的角色有:
● 抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
● 具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。
● 装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。
● 具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。
接口:
public interface Component {
public void sampleOperation();
}
具体构件:
public class ConcreteComponent implements Component {
@Override
public void sampleOperation() {
// 写相关的业务代码
}
}
装饰角色:
public class Decorator implements Component{
private Component component;
public Decorator(Component component){
this.component = component;
}
@Override
public void sampleOperation() {
// 委派给构件
component.sampleOperation();
}
}
具体装饰角色:
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void sampleOperation() {
super.sampleOperation();
// 写相关的业务代码
}
}
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void sampleOperation() {
super.sampleOperation();
// 写相关的业务代码
}
}
大致流程类似于流的封装:
<pre name="code" class="java" style="line-height: 27.999998092651367px;">1.<span style="white-space:pre"> </span>InputStream ins = new FileInputStream();
<span style="white-space:pre"> </span>DataInputStream dis = new DataInputStream(ins);
2. ByteArrayInputStream bai = new ByteArrayInputStream();
<span style="font-family: 'ms shell dlg'; font-size: 12px;">DataInputStream </span><span style="font-size: 12px; font-family: 'ms shell dlg';">dis = new DataInputStream(bai);</span>