装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供l比继承更有弹性的替代方案。装饰者和被装饰者有相同的超类型,你可以用一个或多个装饰者包装一个对象。既然装饰者和被装饰者有相同的超类型,所以在任何需要原始对象(被装饰者)的场合,可以用装饰过的对象替换它。装饰者可以在所委托被装饰者的行为之前或之后加上自己的行为,已达到特定的目的。对象可以在任何时候被装饰,所以可以在运行时动态地、不限量地用你喜欢的装饰者来装饰对象。
类图:
源代码如下:
package decorator; /** * 饮料的超类 * @author <span style="font-family: Arial, Helvetica, sans-serif;">Arvon</span> * */ public abstract class Beverage { String description = "Unknown Beverage"; public String getDescription() { return description; } public abstract float cost(); }
package decorator; /** * 一种饮料 被装饰者 * @author <span style="font-family: Arial, Helvetica, sans-serif;">Arvon</span><pre name="code" class="java">
* */public class HouseBlend extends Beverage {public HouseBlend() {super();description = "House Blend Coffee";}@Overridepublic float cost() {// TODO Auto-generated method stubreturn 0.89f;}}
package decorator; /** * 佐料装饰类 佐料超类 * @author Administrator * */ public abstract class CondimentDecorator extends Beverage { public Beverage mBeverage; @Override public abstract String getDescription(); @Override public abstract float cost(); }
package decorator; /** * 一种佐料 装饰者 * @author Administrator * */ public class Milk extends CondimentDecorator { public Milk(Beverage mBeverage) { this.mBeverage = mBeverage; } @Override public String getDescription() { // TODO Auto-generated method stub return "Milk " + mBeverage.getDescription(); } @Override public float cost() { return .20f + mBeverage.cost(); } }
package decorator; /** * 一种佐料 装饰者 * @author Administrator * */ public class Mocha extends CondimentDecorator { public Mocha(Beverage mBeverage) { super(); this.mBeverage = mBeverage; } @Override public String getDescription() { // TODO Auto-generated method stub return "Mocha "+mBeverage.getDescription(); } @Override public float cost() { // TODO Auto-generated method stub return 1.2f + mBeverage.cost(); } }
package decorator; /** * for testing * @author Administrator * */ public class StarbuzzCoffee { public static void main(String[] args) { // TODO Auto-generated method stub Beverage mBeverage = new HouseBlend(); System.out.println(mBeverage.getDescription() + " $" + mBeverage.cost()); mBeverage = new Milk(mBeverage); System.out.println(mBeverage.getDescription() + " $" + mBeverage.cost()); mBeverage = new Mocha(mBeverage); System.out.println(mBeverage.getDescription() + " $" + mBeverage.cost()); } }
程序的输出:
House Blend Coffee $0.89
Milk House Blend Coffee $1.09
Mocha Milk House Blend Coffee $2.29
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-13 16:38:55