1.对装饰者模式的理解
装饰者模式就像是一个被打包的快递,一般有一个超类,其下分为主体和装饰者(decorator),装饰者不能独立实例化,例如咖啡店的调味品(牛奶,巧克力等)不能独立咖啡出售,实例化时必须要传入一个被包裹好的对象。
2.用装饰者模式实现咖啡馆的代码实例
a.首先是一个抽象超类Drink
<span style="font-size:18px;">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();
}</span>
b.Coffee的主体父类
<span style="font-size:18px;">public class Coffee extends Drink {
@Override
public float cost() {
// TODO Auto-generated method stub
return super.getPrice();
}
}</span>
Coffee下的每一种具体咖啡品种进行Price与Description的设置
1.Decaf
public class Decaf extends Coffee {
public Decaf()
{
super.setDescription("Decaf");
super.setPrice(3.0f);
}
}
2.LongBlack
public class LongBlack extends Coffee{
public LongBlack()
{
super.setDescription("LongBlack");
super.setPrice(6.0f);
}
}
c.装饰者(decorator)的实现代码(此时为具体的调味品)
Decorator为装饰者的主体父类
public class Decorator extends Drink {
private Drink Obj;
public Decorator(Drink Obj){
this.Obj=Obj;
};
@Override
public float cost() {
// TODO Auto-generated method stub
return super.getPrice()+Obj.cost();
}
@Override
public String getDescription()
{
return super.description+"-"+super.getPrice()+"&&"+Obj.getDescription();
}
}
1.Chocolate 传入一个Drink对象
public class Chocolate extends Decorator {
public Chocolate(Drink Obj) {
super(Obj);
// TODO Auto-generated constructor stub
super.setDescription("Chocolate");
super.setPrice(3.0f);
}
}
2.Milk
传入一个Drink对象
public class Milk extends Decorator {
public Milk(Drink Obj) {
super(Obj);
// TODO Auto-generated constructor stub
super.setDescription("Milk");
super.setPrice(2.0f);
}
}
运行代码
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);
order=new Chocolate(order);
System.out.println("order2 price:"+order.cost());
System.out.println("order2 desc:"+order.getDescription());
}