定义一个代表被装饰事物的接口:
public interface Coffee {
public String getCoffer();
public double getPrice();
}
最初的具体事物:
public class Starbucks implements Coffee {
@Override
public String getCoffer() {
return "星巴克";
}
@Override
public double getPrice() {
return 10D;
}
}
被装饰后的具体事物:
public class Seasoning implements Coffee {
private Coffee coffee;
public Seasoning(Coffee coffee) {
this.coffee = coffee;
}
@Override
public String getCoffer() {
return coffee.getCoffer();
}
@Override
public double getPrice() {
return coffee.getPrice();
}
}
一号装饰器:
public class SeasoningOne extends Seasoning implements Coffee {
public SeasoningOne(Coffee coffee) {
super(coffee);
}
@Override
public String getCoffer() {
return super.getCoffer() + " 糖";
}
@Override
public double getPrice() {
return super.getPrice() + 1.0D;
}
}
二号装饰器:
public class SeasoningTwo extends Seasoning implements Coffee {
public SeasoningTwo(Coffee coffee) {
super(coffee);
}
@Override
public String getCoffer() {
return super.getCoffer() + " 牛奶";
}
@Override
public double getPrice() {
return super.getPrice() + 5.0D;
}
}
三号装饰器:
public class SeasoningThree extends Seasoning implements Coffee {
public SeasoningThree(Coffee coffee) {
super(coffee);
}
@Override
public String getCoffer() {
return super.getCoffer() + " 摩卡";
}
@Override
public double getPrice() {
return super.getPrice() + 3.0D;
}
}
使用者:
public class Consumer {
public static void main(String[] args) {
Coffee coffee = new SeasoningOne(new Seasoning(new Starbucks()));
System.out.println(coffee.getCoffer() + ":" + coffee.getPrice());
coffee = new SeasoningTwo(new SeasoningOne(new Seasoning(
new Starbucks())));
System.out.println(coffee.getCoffer() + ":" + coffee.getPrice());
coffee = new SeasoningThree(new SeasoningTwo(new SeasoningOne(
new Seasoning(new Starbucks()))));
System.out.println(coffee.getCoffer() + ":" + coffee.getPrice());
}
}
时间: 2024-11-13 08:56:27