买不同口味的咖啡,学习中间的思想
Food
package decorator;
/**
* @version 1.0
* @date 2021/10/12 17:33
*/
public abstract class Food {
//价格
public abstract int cost();
}
Condiment
package decorator;
/**
* @version 1.0
* @date 2021/10/12 17:35
*/
public abstract class Condiment extends Food{
//被添加的那个饮料
protected Food drink;
}
Coffee
package decorator;
/**
* @version 1.0
* @date 2021/10/12 17:34
*/
public class Coffee extends Food{
@Override
public int cost() {
return 40;
}
}
Milk
package decorator;
/**
* @version 1.0
* @date 2021/10/12 17:41
*/
public class Milk extends Condiment{
public Milk(Food drink) {
this.drink = drink;
}
@Override
public int cost() {
return 10 + drink.cost();
}
}
Sugar
package decorator;
/**
* @version 1.0
* @date 2021/10/12 17:38
*/
public class Sugar extends Condiment{
public Sugar(Food drink) {
this.drink = drink;
}
//总价格
@Override
public int cost() {
return 1 + drink.cost();
}
}
Tea
package decorator;
/**
* @version 1.0
* @date 2021/10/12 17:42
*/
public class Tea extends Condiment{
public Tea(Food drink) {
this.drink = drink;
}
//总价格
@Override
public int cost() {
return 5 + drink.cost();
}
}
Main
package decorator;
/**
* @version 1.0
* @date 2021/10/12 17:43
*/
public class Main {
public static void main(String[] args) {
Food coffee = new Coffee();
Food milk = new Milk(new Sugar(new Tea(new Coffee())));
System.out.println(coffee.cost());
System.out.println(milk.cost());
}
}
装饰者模式设计思想,在IO流中使用过。