一、设计思想
动态的将责任附加到对象上,若要扩展功能,装饰者提供了比继承更具有弹性的替代方案。装饰者就是可以包装一个对象,不断嵌套要被装饰的对象,用装饰者的功能拓展被装饰者的功能。以下是一个饮料加调料算钱问题。
饮料加调料问题
二、Demo
(1)饮料加调料算钱问题
首先设计一个超类代表饮料,然后不同类型饮料继承自它,然后设计一个装饰者的接口继承自饮料超类,然后具体实现装饰者。
饮料超类:
public abstract class Beverage {
String description;
public String getDescription() {
return description;
}
public abstract int cost() ;
}
饮料实现类:
public class HouseBlend extends Beverage {
public HouseBlend(String descri) {
description=descri;
}
@Override
public int cost() {
return 3;
}
}
public class DarkRoast extends Beverage{
public DarkRoast(String descri) {
description=descri;
}
@Override
public int cost() {
return 5;
}
}
装饰者接口:
public abstract class CondimentDecorator extends Beverage {
public abstract String getDescription();
}
装饰者实现类:
public class Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage=beverage;
}
public String getDescription() {
return beverage.getDescription()+",Mocha";
}
public int cost() {
// TODO 自动生成的方法存根
return 2+beverage.cost();
}
}
public class Whip extends CondimentDecorator {
Beverage beverage;
public Whip(Beverage beverage) {
this.beverage=beverage;
}
@Override
public String getDescription() {
// TODO 自动生成的方法存根
return beverage.getDescription()+",Whip";
}
@Override
public int cost() {
// TODO 自动生成的方法存根
return 2+beverage.cost();
}
}
测试代码:
public class Test {
public static void main(String[] args) {
DarkRoast roast=new DarkRoast("DarkRoast");
System.out.println("Description:"+roast.getDescription()+" cost:"+roast.cost());
Beverage beverage1=new DarkRoast("DarkRoast");
beverage1=new Mocha(beverage1);
beverage1=new Mocha(beverage1);
beverage1=new Whip(beverage1);
System.out.println("Description:"+beverage1.getDescription()+" cost:"+beverage1.cost());
}
}
运行结果:
运行结果
网友评论