設計模式之裝飾者模式

裝飾者模式:動態的將新功能附加到對象上,在對象功能擴展方面,它比繼承更有彈性。

一、咖啡館訂單項目

1)、咖啡種類 : Espresso、ShortBlack、LongBlack、Decaf
2)、調料 : Milk、Soy、Chocolate
3)、擴展性好、改動方便、維護方便

下面這個方案會類爆炸:
在這裏插入圖片描述

二、裝飾者模式

在這裏插入圖片描述

1、Drink抽象類

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基類

public  class Coffee extends Drink {

	@Override
	public float cost() {
		return super.getPrice();
	}
}

2)、Decaf類

public class Decaf extends Coffee {
	public Decaf()
	{
		super.setDescription("Decaf");
		super.setPrice(3.0f);
	}
}

3)、Espresso類

public class Espresso extends Coffee{
	public Espresso(){
		super.setDescription("Espresso");
		super.setPrice(4.0f);
	}
}

4)、LongBlack類

public class LongBlack extends Coffee{
	public LongBlack(){
		super.setDescription("LongBlack");
		super.setPrice(6.0f);
	}
}

3、Decorator類及其實現類

1)、Decorator基類

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類

public class Chocolate extends Decorator {

	public Chocolate(Drink Obj) {		
		super(Obj);
		super.setDescription("Chocolate");
		super.setPrice(3.0f);
	}
}

3)、Milk類

public class Milk extends Decorator {

	public Milk(Drink Obj) {		
		super(Obj);
		super.setDescription("Milk");
		super.setPrice(2.0f);
	}
}

4、Decorator類及其實現類

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());	
	}
}

三、java中裝飾者模式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章