装饰器模式
装饰器模式也叫包装模式,是指在不改变原有对象的基础上,将功能附加到对象上,提供比集成更有弹性的替代方案。属于结构型模式
适用场景
- 用于扩展一个类的功能或给一个类添加附加职责
- 动态的给一个对象添加功能,这些功能可以在动态的撤销
案例
public interface Component {
void operation();
}
public class ConcreteComponent implements Component {
public ConcreteComponent() {
System.out.println("创建具体构件角色");
}
@Override
public void operation() {
System.out.println("调用具体构件角色的方法operation()");
}
}
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedFunction();
}
public void addedFunction() {
System.out.println("为具体构件角色增加额外的功能addedFunction()");
}
}
public abstract class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
public class Test {
public static void main(String[] args) {
ConcreteComponent concreteComponent = new ConcreteComponent();
ConcreteDecorator concreteDecorator = new ConcreteDecorator(concreteComponent);
concreteDecorator.operation();
}
}
// 输出
创建具体构件角色
调用具体构件角色的方法operation()
为具体构件角色增加额外的功能addedFunction()
装饰器模式的优点
- 采用装饰模式扩展对象的功能比采用继承方式更加灵活。
- 可以设计出多个不同的具体装饰类,创造出多个不同行为的组合。
装饰器模式的缺点
- 装饰模式增加了许多子类,如果过度使用会使程序变得很复杂。
源码中的装饰器模式
java.io中的InputStream/OutputStream
InputStream fileInputStream = new FileInputStream(new File("demo.txt"));
InputStream bin = new BufferedInputStream(fileInputStream);
DataInputStream din = new DataInputStream(bin);
int data = din.readInt();