装饰着 体现了开闭原则 对扩展开放,
基本类pojo
package com.founder.decorative;
/**
* @author qincy
* 基本类型 抽象类
*/
public abstract class Basic {
private String description = "Basic ";
public String getDescription() {
return description;
}
public Basic() {
// TODO Auto-generated constructor stub
}
public abstract double cost();
}
实现
package com.founder.decorative;
/**
* @author qincy
* 装饰 修饰类 不同
*/
public class AchieveTest1 extends BasicDecorative {
private Basic ac;
/**
* 重点在这里通过构造函数 对Basic 对象 进行 装饰
* @param ac
*/
public AchieveTest1(Basic ac) {
this.ac = ac;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return ac.getDescription() + " === AchieveTest1";
}
public double cost() {
return 1 + ac.cost();
}
}
package com.founder.decorative;
public class AchieveTest2 extends BasicDecorative {
private Basic ac;
public AchieveTest2(Basic ac) {
this.ac = ac;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return ac.getDescription() + " === AchieveTest2";
}
public double cost() {
return 2 + ac.cost();
}
}
。。。
装饰者类
package com.founder.decorative;
/**
* @author qincy
* 装饰者的抽象类
*/
public abstract class BasicDecorative extends Basic {
public abstract String getDescription();
}
实现装饰者
package com.founder.decorative;
/**
* @author qincy
* 形成 不同的类
*/
public class BasicExtends1 extends Basic {
private String descrption;
public BasicExtends1() {
descrption="BasicExtends1";
System.out.print(descrption);
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 10;
}
}
package com.founder.decorative;
public class BasicExtends2 extends Basic {
private String descrption;
public BasicExtends2() {
descrption="BasicExtends20";
System.out.print(descrption);
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 20;
}
}
mian
package com.founder.decorative;
public class main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Basic bd= new BasicExtends1();
System.out.println(bd.getDescription()+" "+bd.cost());
Basic bd2= new BasicExtends2();
bd2 = new AchieveTest1(bd2);
bd2 = new AchieveTest2(bd2);
bd2 = new AchieveTest3(bd2);
bd2 = new AchieveTest4(bd2);
System.out.println(bd2.getDescription()+" "+bd2.cost());
Basic bd3= new BasicExtends3();
bd3 = new AchieveTest1(bd3);
bd3 = new AchieveTest2(bd3);
bd3 = new AchieveTest3(bd3);
//bd3 = new AchieveTest4(bd3);
System.out.println(bd3.getDescription()+" "+bd3.cost());
}
}
results
BasicExtends1Basic 10.0
BasicExtends20Basic === AchieveTest1 === AchieveTest2 === AchieveTest3 === AchieveTest4 30.0
BasicExtends 30Basic === AchieveTest1 === AchieveTest2 === AchieveTest3 36.0