装饰者模式:动态的将新功能附加到对象上,在对象功能扩展方面,它比继承更有弹性。
一、咖啡馆订单项目
1)、咖啡种类 : Espresso、ShortBlack、LongBlack、Decaf 2)、调料 : Milk、Soy、Chocolate 3)、扩展性好、改动方便、维护方便
下面这个方案会类爆炸:
二、装饰者模式
1、Drink抽象类
代码语言:javascript复制public abstract class Drink {
public String description="";
private float price=0f;;
public void setDescription(String description){
this.description=description;
}
public String getDescription(){
return description "-" this.getPrice();
}
public float getPrice(){
return price;
}
public void setPrice(float price){
this.price=price;
}
public abstract float cost();
}
2、Coffee类及其实现类
1)、Coffee基类
代码语言:javascript复制public class Coffee extends Drink {
@Override
public float cost() {
return super.getPrice();
}
}
2)、Decaf类
代码语言:javascript复制public class Decaf extends Coffee {
public Decaf()
{
super.setDescription("Decaf");
super.setPrice(3.0f);
}
}
3)、Espresso类
代码语言:javascript复制public class Espresso extends Coffee{
public Espresso(){
super.setDescription("Espresso");
super.setPrice(4.0f);
}
}
4)、LongBlack类
代码语言:javascript复制public class LongBlack extends Coffee{
public LongBlack(){
super.setDescription("LongBlack");
super.setPrice(6.0f);
}
}
3、Decorator类及其实现类
1)、Decorator基类
代码语言:javascript复制public class Decorator extends Drink {
private Drink Obj;
public Decorator(Drink Obj){
this.Obj=Obj;
};
@Override
public float cost() {
return super.getPrice() Obj.cost();
}
@Override
public String getDescription(){
return super.description "-" super.getPrice() "&&" Obj.getDescription();
}
}
2)、Chocolate类
代码语言:javascript复制public class Chocolate extends Decorator {
public Chocolate(Drink Obj) {
super(Obj);
super.setDescription("Chocolate");
super.setPrice(3.0f);
}
}
3)、Milk类
代码语言:javascript复制public class Milk extends Decorator {
public Milk(Drink Obj) {
super(Obj);
super.setDescription("Milk");
super.setPrice(2.0f);
}
}
4、Decorator类及其实现类
代码语言:javascript复制public class CoffeeBar {
public static void main(String[] args) {
Drink order;
order=new Decaf();
System.out.println("order1 price:" order.cost());
System.out.println("order1 desc:" order.getDescription());
System.out.println("****************");
order=new LongBlack(); // 一杯黑咖啡
order=new Milk(order); // 一杯加牛奶的黑咖啡
order=new Chocolate(order); // 一杯加Chocolate加牛奶的黑咖啡
order=new Chocolate(order); // 一杯加两份Chocolate加牛奶的黑咖啡
System.out.println("order2 price:" order.cost());
System.out.println("order2 desc:" order.getDescription());
}
}