一、概述
1、定义
Attach additional responsibilities to an object dynamically keeping the same interface.Decorators provide a flexible alternative to subclassing for extending functionality.(动态的给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活)
2、通用类图
二、通用源码
Component抽象构件:
Component是一个接口或者是抽象类,就是它定义我们最核心的对象,也就是最原始的对象。
public abstract class Component {
//抽象的方法
public abstract void operate();
}
ConcreteComponent具体构件:
ConcreteComponent是最核心,最原始、最基本的接口或抽象类的实现,是我们要装饰的对象
public class ConcreteComponent extends Component {
@Override
public void operate() {
System.out.println("具体实现");
}
}
Decorator装饰角色:
一般是抽象类,聚合了Component
接口。
//抽象装饰者
public abstract class Decorator extends Component {
private Component component=null;
//通过构造函数传递被修饰者
public Decorator(Component component){
this.component=component;
}
//委托给被修饰者执行
@Override
public void operate() {
this.component.operate();
}
}
具体装饰角色:
public class ConcreteDecorator extends Decorator {
//定义被修饰者
public ConcreteDecorator(Component component) {
super(component);
}
//定义自己的修饰方法
private void decorator(){
System.out.println("修饰");
}
@Override
public void operate() {
this.decorator();
super.operate();
}
}
注:原始方法和装饰方法的执行顺序在具体的装饰类中是固定的,可以通过方法重载实现多种执行顺序。
三、装饰模式的应用
1、优点
- 装饰类和被装饰类可以独立发展,不会相互耦合。也就是说,Component类无需知道Decorator类,Decorator类是从外部来扩展Component的功能,而Decorator也不用知道具体的构件。
- 装饰模式是继承关系的一个替代方案,从而解决继承带来的类膨胀与强侵入问题;
- 装饰模式可以动态的扩展一个实现类的功能。
2、缺点
- 多层的装饰会使系统比较复杂,即一个实现类的功能若用多个装饰类进行装饰,则会增加该实现类的耦合度。
3、使用场景
- 需要扩展一个类的功能,或者是给一个类增加附加功能;
- 需要动态的给一个对象增加功能,这些功能可以再动态的撤销;
- 需要为一批兄弟类进行改装和添加功能的场景。
四、IO源码分析
1、IO源码结构与装饰模式
InputStream
相当于我们装饰模式中通用类图的Component
;FileInputStream
类,继承自InputStream
,是具体构建的角色;FilterInputStream
类,继承自InputStream
,相当于通用类图中的Decorator
角色,DataInputStream
类,继承自FilterInputStream
,是具体的修饰角色。
2、IO源码结构类图
3、部分源码
装饰类FilterInputStream
:
public
class FilterInputStream extends InputStream {
//持有的被装饰者对象
protected volatile InputStream in;
//初始化的时候就指定被装饰者
protected FilterInputStream(InputStream in) {
this.in = in;
}
//被装饰者方法的调用
public int read() throws IOException {
return in.read();
}
}
具体的装饰类DataInputStream
:
public
class DataInputStream extends FilterInputStream implements DataInput {
//构造器:指定被修饰者
public DataInputStream(InputStream in) {
super(in);
}
//扩展的功能,即修饰
public final void readFully(byte b[], int off, int len) throws IOException {
if (len < 0)
throw new IndexOutOfBoundsException();
int n = 0;
while (n < len) {
int count = in.read(b, off + n, len - n);
if (count < 0)
throw new EOFException();
n += count;
}
}
public final char readChar() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (char)((ch1 << 8) + (ch2 << 0));
}
}
4、main
方法中的调用
main()方法中调用方式也和我们的装饰模式调用类似。
DataInputStream dis = new DataInputStream(new FileInputStream("d:\\text.txt"));