`
pan_java
  • 浏览: 286181 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

hand first 设计模式 - 装饰者模式

阅读更多
所有饮料抽象类
public abstract class Beverage {

	String description = "unknown beverage";

	public String getDescription() {
		return description;
	}

	public abstract double cost();

}


装饰者抽象类
public abstract class CondimentDecorator extends Beverage {

	public abstract String getDescription();
	

}


浓咖啡
public class Espresso extends Beverage {

	public Espresso(){
		description = "Espresso";
	}
	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return 1.99;
	}

}



佐料(装饰者)摩卡类
public class Mocha extends CondimentDecorator {

	Beverage beverage;
	
	public Mocha(Beverage beverage){
		this.beverage = beverage;
	}
	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		System.out.println(beverage.getDescription());
		
		return beverage.getDescription()+",Mocha";
	}

	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return .20 +beverage.cost();
	}

}


public class StarbuzzCoffee {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//单纯的咖啡
		Beverage beverage = new Espresso();
		
                   //加入摩卡的咖啡
		beverage = new Mocha(beverage);
		
		System.out.println(beverage.getDescription()+" $ "+beverage.cost());
}

}


设计原则
对扩展开放,对修改关闭
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics