demo事例:用装饰模式编写给人装饰比如穿衣、库、鞋等程序
Persion.java
/**
* 人
* @author Persion
*
*/
public class Persion {
private String name;
public Persion(){}
public Persion(String name){
this.name = name;
}
public void show(){
System.err.print("装扮:"+name+" ");
}
}
Finery.java
public class Finery extends Persion{
protected Persion persion;
public void Decorate(Persion persion){
this.persion=persion;
}
public void show(){
if(persion != null){
persion.show();
}
}
}
BigTrouser .java
public class BigTrouser extends Finery {
@Override
public void show(){
System.out.print("裤子 ");
persion.show();
}
}
TShrts .java
public class TShrts extends Finery{
@Override
public void show(){
System.out.print("大T恤 ");
persion.show();
}
}
Test .java
/**
* 装饰模式
* @author lucksheep
*
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Persion persion=new Persion("小肥羊");
TShrts shrts=new TShrts();
BigTrouser bt=new BigTrouser();
shrts.Decorate(persion);
bt.Decorate(shrts);
bt.show();
}
}
装饰模式总结下:
1、一般呢就是把类中的装饰功能搬移出去,简化原有的类。
2、有效的把类的核心职责和装饰的功能分开,并且可以去除相关类中重复的装饰逻辑