- 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 DarkRoast extends Beverage {
- public DarkRoast() {
- description = "Dark Roast Coffee";
- }
- public double cost() {
- return .99;
- }
- }
- public class Milk extends CondimentDecorator { //加牛奶的咖啡
- Beverage beverage;
- public Milk(Beverage beverage) {
- this.beverage = beverage;
- }
- public String getDescription() {
- return beverage.getDescription() + ", Milk";
- }
- public double cost() {
- return .10 + beverage.cost();
- }
- }
要计算加牛奶的咖啡的价格
Milk milk = new Milk(new DarkRoast ());
milk.cost();