没什么好说的,直接上图(装饰者设计模式的设计思路)
上面就是装饰者模式的总体设计的UML图
然后上代码:
1.接口类
package com.ergouge.decorator;
public interface Coffee {
double getPrice();
String getInformation();
}
2.两种类型的咖啡
package com.ergouge.decorator;
public class Quechao implements Coffee {
@Override
public double getPrice() {
return 10.0;
}
@Override
public String getInformation() {
return "雀巢咖啡";
}
}
//这种咖啡好像没有,自己胡扯的哈
package com.ergouge.decorator;
public class Haohao implements Coffee {
@Override
public double getPrice() {
return 20.0;
}
@Override
public String getInformation() {
return "好好咖啡";
}
}
3.装饰者类
package com.ergouge.decorator;
public class Decorator implements Coffee{
Coffee coffee;
public Decorator(Coffee coffee) {
super();
this.coffee = coffee;
}
@Override
public double getPrice() {
return coffee.getPrice();
}
@Override
public String getInformation() {
return coffee.getInformation();
}
}
4.加了牛奶的
package com.ergouge.decorator; public class AddMilk extends Decorator { public AddMilk(Coffee coffee) { super(coffee); } @Override public String getInformation() { return super.getInformation() + "加了牛奶的"; } }
5.大杯的package com.ergouge.decorator; public class LargeScale extends Decorator { public LargeScale(Coffee coffee) { super(coffee); } @Override public double getPrice() { return super.getPrice() * 1.5; } @Override public String getInformation() { // TODO Auto-generated method stub return super.getInformation() + "L"; } }
6.app类
package com.ergouge.decorator; public class App { public static void main(String[] args) { Coffee coffee = new LargeScale(new AddMilk(new Quechao()));//这里就非常方便了,new了一个加牛奶的大杯 System.out.println(coffee.getInformation()); System.out.println(coffee.getPrice()); } }
输出结果