装饰模式又名包装(Wrapper)模式,装饰模式以客户端透明的方式扩展对象的功能,是继承关系的一种代替方案。
装饰模式其实我们在使用java I/O的时候就已经使用过例如:
//写法一:
FileInputStream fis=new FileInputStream(file);
BufferedInputStream bis=new BufferedInputStream(fis);
DataInputStream dis=new DataInputStream(bis);
//写法二:
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
这就是我们平时使用的包装模式。
下面我们来讲讲它的实现过程:
1、首先FileInputStream、BufferedInputStream 、DataInputStream 三者都实现了同一个接口InputStream.
public abstract class InputStream implement Cloneabe{
//定义流的各种方法
.............
.............
.............
}
public class FileInputStream extends InputStream{
public FileInputStream(InputStream is){
}
//定义或者继承的各种方法
}
public class BufferedInputStream extends FilterInputStream{
public BufferedInputStream(InputStream is){ //is是一个委托对象
super(is);
}
//定义方法和委托对象方法的调用。
}
说明:装饰模式和适配模式中的委托方式和相像,但又不同。设计时装饰模式的会对对象的行为方式进行增强,因为装饰模式可以递增的方式进行再装饰、行为功能也递增,所以装饰模式的的抽象构建角色必须保持一致。 而适配器模式不会对行为功能进行增强,只会对行为就行改变以适应改变的接口。
应用场景:在设计类是需要对类的行为功能就行不断的增强可以使用装饰模式(为什么不使用继承,是因为继承方式是静态写死的,没有装饰模式灵活,但使用装饰模式会增加类对象,使用维护不便)。