设计模式之装饰者模式
作者:互联网
装饰者模式的定义
装饰着模式:动态的将新功能附加到对象上,在对象功能扩展方面,他比继承更有弹性,装饰着模式也体现出了OCP原则
装饰者模式原理
星巴克订单项目:
1.咖啡种类/单品咖啡:Espresso、ShortBlack、LongBlack、Decaf
2.调料:Milk、Soy、Chocolate
3.要求在扩展新的咖啡种类时,具有良好的扩展性、改动方便、维护方便
4.使用OO的来方法计算不同种类咖啡的费用:客户可以点单品咖啡 ,也可以单品咖啡+调料组合
package com.cedric.decorator;
public class Coffee extends Drink{
@Override
public float cost() {
return super.getPrice();
}
}
package com.cedric.decorator;
public class LongBlack extends Coffee{
public LongBlack(){
setDes("LongBlack");
setPrice(5.0f);
}
}
package com.cedric.decorator;
public class ShortBlack extends Coffee{
public ShortBlack(){
setDes("ShortBlack");
setPrice(7.0f);
}
}
package com.cedric.decorator;
public class DeCaf extends Coffee{
public DeCaf(){
setDes("无因咖啡");
setPrice(9.0f);
}
}
package com.cedric.decorator;
public abstract class Drink {
public String des;//描述
private float price = 0.0f;
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
// 计算费用的抽象方法
// 子类来实现
public abstract float cost();
}
package com.cedric.decorator;
// 具体的Decorator,这里就是调味品
public class Chocolate extends Decorator{
public Chocolate(Drink obj) {
super(obj);
setDes("巧克力");
setPrice(3.0f);// 调味品的价格
}
}
package com.cedric.decorator;
public class Milk extends Decorator{
public Milk(Drink obj) {
super(obj);
setDes("牛奶");
setPrice(2.0f);
}
}
package com.cedric.decorator;
public class Soy extends Decorator{
public Soy(Drink obj) {
super(obj);
setDes("豆浆");
setPrice(1.5f);
}
}
package com.cedric.decorator;
public class CofferBar {
public static void main(String[] args) {
// 装饰者模式下的订单:2份巧克力 + 一份牛奶的LongBlack
// 1.点一份LongBlack
Drink order = new LongBlack();
System.out.println(order.getDes() + ":"+ order.cost());
// 2.加入一份牛奶
order = new Milk(order);
System.out.println("加入一份牛奶 :" + order.getDes() + ":"+ order.cost());
// 3.order加入一份巧克力
order = new Chocolate(order);
System.out.println("加入一份牛奶 和 巧克力 :" + order.getDes() + ":"+ order.cost());
// 4.order又加入一份巧克力
order = new Chocolate(order);
System.out.println("加入一份牛奶 和 两份巧克力 :" + order.getDes() + ":"+ order.cost());
// 点一份DeCaf
Drink drink = new DeCaf();
System.out.println(drink.getDes() + drink.getPrice());
}
}
package com.cedric.decorator;
public class Decorator extends Drink{
private Drink obj;
public Decorator(Drink obj){ //组合
this.obj = obj;
}
@Override
public float cost() {
//getPrice自己的价格
return super.getPrice() + obj.cost();
}
@Override
public String getDes() {
// obj.getDes()输出被装饰者信息
return super.des + " " + super.getDes() + "&&" + obj.getDes();
}
}
标签:getDes,obj,模式,装饰,public,cedric,设计模式,order,decorator 来源: https://www.cnblogs.com/cedric1114/p/15394877.html