jdk中的io就是用的装饰模式
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("d:/hello.txt")));
角色
抽象构建角色 component OutputStream
给出一个抽象接口,以规范准备接收附加责任的对象
具体构建角色 concrete component FileOutputStream io中的节点流
定义一个将要接收附加责任的类
装饰角色 decorator FilterOutputStream 类 io中的过滤流
持有一个构建对象的引用,并定义一个与抽象构建接口一致的接口
具体的装饰角色 concrete decorator 继承了FilterOutputStream的 比如DataOutputStream、BufferedOutputStream
负责给构建对象贴上附加的责任
装饰 vs 继承
装饰是扩展对象的功能
继承是扩展类得功能
如果io采用继承 那么 带缓存的 要实现子类, 带data输入的 有要子类 组合起来又要子类,就会产生很多的类
装饰 vs 代理
。。。。。。
/**
* 抽象的构建角色
**/
public interface Component {
public void doSometing();
}
// 具体的构建角色
public class ConcreteComponent implements Component {
@Override
public void doSometing() {
System.out.println("功能A");
}
}
// 装饰角色
public class Decorator implements Component {
private Component component;
public Decorator(Component component){
this.component = component;
}
@Override
public void doSometing() {
component.doSometing();
}
}
// 具体的装饰角色1
public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component component){
super(component);
}
@Override
public void doSometing() {
super.doSometing();
this.doAnotherTing();
}
private void doAnotherTing(){
System.out.println("功能B");
}
}
//具体的装饰角色2
public class ConcreteDecorator2 extends Decorator {
public ConcreteDecorator2(Component component){
super(component);
}
@Override
public void doSometing() {
super.doSometing();
this.doAnotherTing();
}
private void doAnotherTing() {
System.out.println("功能C");
}
}
// 客户端测试代码
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Component component2 = new ConcreteDecorator1(component);
Component component3 = new ConcreteDecorator2(component2);
component3.doSometing();
}
}