设计模式之装饰者模式-笔记

装饰者模式:动态的将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。


设计原则:
类应该对扩展开发,对修改关闭

场景:咖啡店,有些人点低咖啡因咖啡加牛奶、摩卡,有些人点浓缩咖啡加奶泡......,系统可以通过点的咖啡和加的配料计算出价钱,系统可以在不需要修改原有代码的情况下动态添加新的咖啡类或者新的配料


beverage:饮料


建立抽象类:
//实现咖啡抽象类
public abstruct class Beverage{
String description = 'Unknown Beverage';

public String getDescription(){
return description;
}

public abstruct double cost();
}

//实现的配料抽象类,也称为装饰者类
public abstruct class CondimentDecorator extends Beverage{
public abstruct String getDescription();//每个配料类都必须重新实现该方法,这样可以根据不同的配料实现完整的描述
}

//实现各饮料类
public class Expresso extends Beverage{
public Expresso(){
description = "Expresso";
}
public double cost(){
return 1.99;
}
}

public class HouseBlend extends Beverage{
public HouseBlend(){
description = "House Blend Coffee";
}
public double cost(){
return 0.99;
}
}

//实现配料类
public class Mocha extends CondimentDecorator{
Beverage beverage;

public Mocha(Beverage beverage){
this.beverage = beverage;
}
//可以获取完整的描述
public getDescription(){
return beverage.getDescription() + ", Mocha";
}

public double cost(){
return 0.20 + beverage.cost();
}
}

public class Milk extends CondimentDecorator{
Beverage beverage;

public Milk(Beverage beverage){
this.beverage = beverage;
}
//可以获取完整的描述
public getDescription(){
return beverage.getDescription() + ", Milk";
}

public double cost(){
return 0.30 + beverage.cost();
}
}

//测试
public class StarBuzzCoffee{
public static void main(String args[]){
Beverage beverage = new Expresso();
System.out.println(beverage.getDescription()+" $"+beverage.cost());

Beverage beverage2 = new HouseBlend();
beverage2 = new Mocha(beverage2);
beverage2 = new Milk(beverage2)
System.out.println(beverage2.getDescription()+" $"+beverage2.cost())
}
}

//运行结果
Expresso $1.99
House Blend Coffee, Mocha, Milk $1.49

你可能感兴趣的:(设计模式,设计模式,装饰者模式)