装饰模式属于设计模式中较为重要的一个模式了,在jdk IO中也有应用,有没有对下面的这句话很熟悉。
BufferedReader bf=new BufferedReader(new InputStreamReader(new FileInputStream(path)));//字符流读取文件的方式,当然字符流是基于字节流的。
其实这个就是装饰者模式,给FileInputStream添加了一层又一层装饰。
public abstract class Decortor extends Human{
private Human human;
public Decortor(Human human) {
this.human=human;
}
@Override
public void wearCloth() {
human.wearCloth();
}
}
这个就是装饰模式的UML图,
COmponent一般是抽象类或者接口,而Decorator则是继承Component的一个抽象类,内部封装了private的component对象,用来调用方法。
第一步创建抽象类或者接口,里面的是抽象方法 wearCloth。
public abstract class Human {
public abstract void wearCloth();
}
第二步:创建实体类继承抽象类,这个类指的是被装饰的实体,同时还有初始化。
public class RealMan extends Human{
@Override
public void wearCloth() {
System.out.println("我该穿什么呢");
}
}
第三步:创建装饰者的抽象类继承Human抽象类
public abstract class Decortor extends Human{
private Human human;
public Decortor(Human human) {
this.human=human;
}
@Override
public void wearCloth() {
human.wearCloth();
}
}
第四步:创建装饰的类
public class Decortor1 extends Decortor{
public Decortor1(Human human) {
super(human);
}
public void wearCloth(){
super.wearCloth();
System.out.println("先穿大衣");
}
}
public class Decortor2 extends Decortor{
public Decortor2(Human human) {
super(human);
}
public void wearCloth(){
super.wearCloth();
System.out.println("再穿牛仔");
}
}
测试:
@Test
public void test() {
RealMan realMan=new RealMan();
Decortor1 decortor1=new Decortor1(realMan);
Decortor2 decortor2=new Decortor2(decortor1);
decortor2.wearCloth();
}