装饰者模式

             动态的将职责附加到对象上。

系统描述:购买咖啡的系统,购买咖啡时可以加入各种调料,然后结账的时候算上咖啡和调料的钱的总和。

总的饮料抽象类Beverage.java

package cn.beverage.demo;

/**
 * 饮料抽象类
 * 
 * @author wy
 * 
 */
public abstract class Beverage {
	String desc = "unknow Beverage";

	public String getDesc() {
		return this.desc;
	}

	public abstract double cost();
}
 調料抽象類:Condiment.java:装饰者类必须继承最上层的饮料抽象类。

package cn.beverage.demo;

/**
 * 調料抽象類,装饰者类
 * 
 * @author wy
 * 
 */
public abstract class Condiment extends Beverage {

	public abstract String getDesc();
}
2个被装饰类:被装饰类基础最上层的饮料抽象类

package cn.beverage.demo;

/**
 * 被装饰的类
 * 
 * @author wy
 * 
 */
public class Espresso extends Beverage {

	public Espresso() {
		this.desc = "濃縮咖啡";
	}

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

}
package cn.beverage.demo;

/**
 * 被装饰的类
 * 
 * @author wy
 * 
 */
public class HouseBlend extends Beverage {

	public HouseBlend() {
		this.desc = "首选咖啡";
	}

	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return 0.89;
	}

}

再添加两个装饰者:

package cn.beverage.demo;

/**
 * 裝飾者
 * 
 * @author wy
 * 
 */
public class Mocha extends Condiment {

	private Beverage beverage;

	public Mocha(Beverage beverage) {
		this.beverage = beverage;
	}

	@Override
	public String getDesc() {
		// TODO Auto-generated method stub
		return beverage.getDesc() + ",摩卡";
	}

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

}

package cn.beverage.demo;

/**
 * 裝飾者
 * 
 * @author wy
 * 
 */
public class Whip extends Condiment {

	private Beverage beverage;

	public Whip(Beverage beverage) {
		this.beverage = beverage;
	}

	@Override
	public String getDesc() {
		// TODO Auto-generated method stub
		return beverage.getDesc() + ",whip ";
	}

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

}
测试方法:

package cn.beverage.demo;

public class Test {
	public static void main(String[] args) {
		Beverage beverage = new Espresso();
		beverage = new Mocha(beverage);
		System.out.println(beverage.getDesc() + " : " + beverage.cost());

		Beverage beverage2 = new HouseBlend();
                //用摩卡装饰beverage2
beverage2 = new Mocha(beverage2);
		System.out.println(beverage2.getDesc() + " : " + beverage2.cost());

		Beverage beverage3 = new Espresso();
                //用摩卡装饰beverage3
 beverage3 = new Mocha(beverage3);
                //再用whip装饰beverage3
                beverage3 = new Whip(beverage3);
		System.out.println(beverage3.getDesc() + " : " + beverage3.cost());
	}
}

输出结果:

濃縮咖啡,摩卡 : 2.19
首选咖啡,摩卡 : 1.09
濃縮咖啡,摩卡,whip  : 12.19


posted on 2013-12-23 13:56  wyang0126  阅读(111)  评论(0编辑  收藏  举报