設計模式三:裝飾者模式

裝飾者模式動態地將責任附加到對象上。如要擴展功能,裝飾者提供了比繼承更有彈性的替代方案。java

設計原則:類應該對擴展開放,對修改關閉。設計模式

抽象組件Component :測試

Beverage類(能夠是接口也能夠是抽象類)this

package com.sun;

public abstract class Beverage {
	String description = "Unknow Beverage";
	public String getDescription(){
		return description;
	}
	public abstract double cost();
}

具體組件ConcreteComponent:具體組件擴展自 Beverage類設計

DarkRost類code

package com.sun;

public class DarkRost extends Beverage {
	
	public DarkRost(){
		description = "this is DarkRost";
	}
	public double cost() {
		return 0.88;
	}

}

Espresso類對象

package com.sun;

public class Espresso extends Beverage{
	public Espresso(){
		description = "Espresso";
	}
	public double cost(){
		return 1.99;
	}
}

HouseBlend類繼承

package com.sun;

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

}

 

抽象裝飾者Decorator: 必須讓 抽象裝飾者可以取代Beverage,因此將抽象裝飾者擴展自Beverage類接口

CondimentDecorator類ip

package com.sun;

public abstract class CondimentDecorator extends Beverage{
	public abstract String getDescription();
}

具體裝飾者:

Mocha類

package com.sun;

public class Mocha extends CondimentDecorator {
	
	Beverage beverage;
	
	public Mocha(Beverage beverage){
		this.beverage = beverage;
	}
	public String getDescription() {
               /*由於Beverage對象已經被裝飾過,因此這裏不僅是想描述被裝飾者(例如DarkRost),而是連同裝飾者都描述出來(例如「DarkRoast,Mocha」。因此首先利用委託的作法,獲得一個敘述,而後在其後加上附加的敘述。*/
		return beverage.getDescription() +",Mocha";
	}

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

}

Whip類

package com.sun;

public class Whip extends Beverage {
	Beverage beverage;
	public Whip(Beverage beverage){
		this.beverage = beverage;
	}
	
	public String getDescription(){
		return beverage.getDescription() + ", Whip";
	}
	public double cost() {
		return 0.22 + beverage.cost();
	}

}

測試類:StarbuzzCoffee

package com.sun;

public class StarbuzzCoffee {
	public static void main(String[] args) {
		Beverage beverage = new Espresso();
		System.out.println(beverage.getDescription()+"$" + beverage.cost());
		
		Beverage beverage2 = new DarkRost();
 	beverage2 = new Mocha(beverage2); //用Mocha裝飾DarkRost對象
		beverage2 = new Whip(beverage2); //用第二個Mocha裝飾DarkRost對象
		System.out.println(beverage2.getDescription()+"$" + beverage2.cost());
		
		Beverage beverage3 = new HouseBlend();
		beverage3 = new Whip(beverage3); //用Whip裝飾HouseBlend對象
		beverage3 = new Mocha(beverage3); //用Mocha裝飾HouseBlend對象
		System.out.println(beverage3.getDescription() + "$" +beverage3.cost());
	} 
}

測試結果:

Espresso$1.99
this is DarkRost,Mocha, Whip$1.3
House Blend Coffee, Whip,Mocha$1.31

能夠利用工廠和生成器設計模式,能以更好的方式創建被裝飾者對象。

相關文章
相關標籤/搜索