package com.shi.design.director;
/**
* 装饰者模式
* @author shiye
*
*/
public abstract class Drink {
private String desc;//描述
private float price;//价格
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
//计算费用 (需要子类去实现)
public abstract float cost();
}
package com.shi.design.director;
/**
* 所有咖啡的父类 , 对咖啡的所有子类进行对的封装
* @author shiye
*
*/
public abstract class Coffer extends Drink{
@Override
public float cost() {
System.out.println(super.getDesc() + " 的价格为= " + super.getPrice());
return super.getPrice();
}
}
package com.shi.design.director;
/**
* 第一种咖啡
* @author shiye
*
*/
public class CofferSun1 extends Coffer {
public CofferSun1() {
setDesc(" 第一种咖啡 ");
setPrice(5.0f);
}
}
package com.shi.design.director;
/**
* 第二种咖啡
* @author shiye
*
*/
public class CofferSun2 extends Coffer {
public CofferSun2() {
setDesc(" 第二种咖啡 ");
setPrice(8.0f);
}
}
package com.shi.design.director;
/**
* 第三种咖啡
* @author shiye
*
*/
public class CofferSun3 extends Coffer {
public CofferSun3() {
setDesc(" 第三种咖啡 ");
setPrice(30.0f);
}
}
package com.shi.design.director;
/**
* 装饰者
* @author shiye
*
*/
public abstract class Decorator extends Drink {
private Drink drink;
@Override
public float cost() {
// 计算价格 (咖啡的价格 + 调料的价格)
return drink.getPrice() + super.getPrice();
}
@Override
public String getDesc() {
// 描述
return super.getDesc() + "的价格为: " + super.getPrice() + drink.getDesc();
}
public Drink getDrink() {
return drink;
}
public void setDrink(Drink drink) {
this.drink = drink;
}
}
package com.shi.design.director;
/**
* 巧克力 装饰者
* @author shiye
*
*/
public class DecoratorChoclate extends Decorator {
public DecoratorChoclate(Drink drink){
setDrink(drink);
setDesc(" 巧克力 ");
setPrice(9.5f);
}
}
package com.shi.design.director;
/**
* 牛奶装饰者
* @author shiye
*
*/
public class DecoratorMilk extends Decorator {
public DecoratorMilk(Drink drink){
setDrink(drink);
setDesc(" 牛奶 ");
setPrice(3.0f);
}
}
package com.shi.design.director;
/**
* 豆浆装饰者
* @author shiye
*
*/
public class DecoratorSoy extends Decorator {
public DecoratorSoy(Drink drink){
setDrink(drink);
setDesc(" 豆浆 ");
setPrice(1.5f);
}
}
package com.shi.design.director;
/**
* 装饰者模式测试
* @author shiye
*
*/
public class Test {
public static void main(String[] args) {
Drink order = new CofferSun2();
System.out.println(" 一份" + order.getDesc() + "咖啡的总价格为: " + order.cost());
order = new DecoratorChoclate(order);
System.out.println(" 加了一份" + order.getDesc() + "咖啡的总价格为: " + order.cost());
order = new DecoratorMilk(order);
System.out.println(" 加了一份" + order.getDesc() + "咖啡的总价格为: " + order.cost());
}
}