本篇主要介绍常用的一个设计模式——装饰器模式。
简介
装饰器模式:动态的将责任加到对象上,能扩展对象的功能,且比使用继承来达到扩展对象的功能更有弹性。
应用场合:设计的类数量过多、设计死板且父类加入的功能子类不能全部适用。JAVA中的IO就大量用到了此模式。
Component表示抽象的父类,ConcreteComponent表示具体的子类,Decorator表示装饰器,用来装饰ConcreteComponent,Decorator可以是抽象的,它持有指向Component的引用。ConcreteDecorator表示被装饰后的对象。下面我将用代码例子来实现图中的关系。
实例代码
Component.java
public interface Component {
void run();
}
ConcreteComponent.java—— 实现了Component
public class ConcreteComponent implements Component {
@Override
public void run() {
System.out.println("运行ConcreteComponent的run()方法");
}
}
Decorator.java ——这里的装饰器并没使用抽象接口,而是使用了具体的装饰器。
public class Decorator implements Component {
private Component component;
//使用构造函数,获得component的引用
public Decorator(Component component) {
this.component = component;
}
@Override
public void run() {
System.out.println("装饰前的方法");
component.run();
System.out.println("装饰后的方法");
}
}
AnotherDecorator.java ——另外一个装饰器。
public class AnotherDecorator implements Component {
private Component component;
//持有component引用
public AnotherDecorator(Component component) {
this.component = component;
}
@Override
public void run() {
System.out.println("另一个装饰前的方法");
component.run();
System.out.println("另一个装饰后的方法");
}
}
测试代码DecoratorTest.java
public class DecoratorTest {
public static void main(String[] args) {
Component component = new ConcreteComponent();
//使用Decorator包装ConcreteComponent
component = new Decorator(component);
//使用AnotherDecorator包装Decorator
component = new AnotherDecorator(component);
//执行使用AnotherDecorator包装后的run()方法。
component.run();
}
}
//控制台输出如下:
/*
另一个装饰前的方法
装饰前的方法
运行ConcreteComponent的run()方法
装饰后的方法
另一个装饰后的方法
*/
java中的IO类库就大量用到了装饰器模式。
//这里使用BufferedInputStream包装了FileInputStream,使得输入流有了缓冲的特性
InputStream in = new BufferedInputStream(new FileInputStream("file.txt"));