说起装饰模式,大家能联想到的应该是java中IO哪块的逻辑。下面给大家说说,我理解的装饰模式!
装饰模式由以下4个部分组成:
1.抽象构建角色:给出一个规范接口,以规范准备附加责任的对象。例(InputStream,OutputStream).
2.具体构建角色:定义一个附加责任的类。例(FileInputStream,FileOutputStream).
3.装饰角色:持有一个构建对象的引用,并定义一个与抽象构件接口一致的接口。例(FilterInputStream,FilterOutputStream).
4.具体装饰角色:负责给构件对象添上附加的责任。例(DataInputStream,DataOutputStram.BufferedInputStream,BufferedOutputStram).
下面给大家演示一下简单的代码:
(1).抽象构建角色
public interface Component {
public void doSomething();//抽象构建角色
}
2.需要被装饰的类对象(装饰角色)
public class ConcreteComponent implements Component {
@Override
public void doSomething() {//具体构建角色
// TODO Auto-generated method stub
System.out.println("我是一个功能A");
}
}
(3).装饰某个类对象的父类角色(具体构建角色)
public class Decorator implements Component {
private Component component;//装饰角色
public Decorator(Component component){
this.component = component;
}
@Override
public void doSomething() {
// TODO Auto-generated method stub
component.doSomething();
}
}
(4).装饰功能1(具体装饰角色A)
public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component component){//具体装饰角色
super(component);
}
@Override
public void doSomething() {
// TODO Auto-generated method stub
super.doSomething();
this.doAnthorthing();
}
private void doAnthorthing(){
System.out.println("我有特殊功能1");
}
}
(5).装饰功能2(具体装饰角色B)
public class ConcreteDecorator2 extends Decorator {
public ConcreteDecorator2(Component component){//具体装饰角色
super(component);
}
@Override
public void doSomething() {
// TODO Auto-generated method stub
super.doSomething();
this.doAnthorthing();
}
private void doAnthorthing(){
System.out.println("我有特殊功能2");
}
}
测试类
public class ComponentTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//节点流
Component component = new ConcreteComponent();
//过滤流
Component component1 = new ConcreteDecorator1(component);
//过滤流
Component component2 = new ConcreteDecorator2(component1);
component2.doSomething();
}
}
此时,指定component2时,因为一开始的concreateComponent对象已经被一层一层的装饰了两个功能,所以此时运行component2.doSomething时,就是已经装饰了的类对象。