装饰器模式应用于下面的场景:
不确定客户端对某个类的对象需要什么功能,所以一般只给客户端一个默认的实现,具有基本的功能。比如对于InputStream这个抽象类会有一个FileInputStream的实现,这个实现提供文件输入流的基本功能。但是有时候客户端会加个缓冲功能,或者想把一个InputStream或者其子类转换成DataInputStream为了实现跨平台,我们可以把已经传在的对象传进构造器即可,这就是装饰器模式。
下面有一个简单的装饰器模式例子,
package net.liuyx.test;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
public class DecoratorTest {
public static void main(String[] args) {
Woman woman;
woman = new ChineseWoman();
woman.cook();
System.out.println("===============================");
System.out.println("Descorate the woman with knowledge");
System.out.println("The new woman then have knowledge decorated!");
System.out.println("===============================");
Knowledge knowWoman = new Knowledge(woman);
knowWoman.cook();
System.out.println("===============================");
System.out.println("Descorate the woman with beauty");
System.out.println("The new woman then have beauty decorated!");
System.out.println("===============================");
Beautify beautifulWoman = new Beautify(woman);
beautifulWoman.cook();
System.out.println("===============================");
System.out.println("Descorate the woman with beauty and knowledge");
System.out
.println("The new woman then have beauty and knowledge decorated!");
System.out.println("===============================");
Knowledge perfectWoman = new Knowledge(new Beautify(woman));
perfectWoman.cook();
}
}
interface Woman {
void cook();
}
class ChineseWoman implements Woman {
@Override
public void cook() {
System.out.println("这个女人能做饭");
}
}
/**
*装饰器类含有被装饰类接口的一个引用,而且装饰器类与被装饰器类必须有同一个接口,
*这样就能把一个子类对象传到装饰器构造器内,从而达到装饰的作用
* @author liuyx
*
*/
class Descorator implements Woman {
private Woman woman;
public Descorator(Woman woman) {
this.woman = woman;
}
@Override
public void cook() {
woman.cook();
}
}
class Knowledge extends Descorator {
public Knowledge(Woman woman) {
super(woman);
}
private void haveKnowledge() {
System.out.println("这个女人做法挺有章法");
}
@Override
public void cook() {
super.cook();
haveKnowledge();//用知识武装女人
}
}
class Beautify extends Descorator {
public Beautify(Woman woman) {
super(woman);
}
private void haveBeautify() {
System.out.println("这个女人饭菜做得很漂亮");
}
@Override
public void cook() {
super.cook();
haveBeautify();//用漂亮的厨艺武装女人
}
}