/*
定义最顶层接口
*/
public interface Drink {
String desc();//商品描述
int cost();//商品价格
}
/*
被装饰者的父类
*/
public class Tea implements Drink{
@Override
public String desc() {
return null;
}
@Override
public int cost() {
return 0;
}
}
/*
被装饰者一
*/
public class IceTea extends Tea{
@Override
public String desc() {
return "ice tea";
}
@Override
public int cost() {
return 10;
}
}
/*
被装饰者二
*/
public class GreenTea extends Tea{
@Override
public String desc() {
return "green tea";
}
@Override
public int cost() {
return 20;
}
}
/*
被装饰者三
*/
public class BlackTea extends Tea{
@Override
public String desc() {
return "black tea";
}
@Override
public int cost() {
return 30;
}
}
/*
装饰者的基类
*/
public class Decorator implements Drink{
private Drink drink;//装饰者持有被装饰者的引用 这样才能进行装饰
public Decorator(Drink drink) {
this.drink = drink;
}
@Override
public String desc() {
return drink.desc();
}
@Override
public int cost() {
return drink.cost();
}
}
/*
装饰者一
*/
public class Milk extends Decorator{
public Milk(Drink drink) {
super(drink);
}
@Override
public String desc() {
return super.desc() + " 牛奶";
}
@Override
public int cost() {
return super.cost() + 1;
}
}
/*
装饰者二
*/
public class Sugar extends Decorator{
public Sugar(Drink drink) {
super(drink);
}
@Override
public String desc() {
return super.desc() + " 糖";
}
@Override
public int cost() {
return super.cost() + 2;
}
}
设计模式四之装饰者模式
最新推荐文章于 2023-05-04 21:03:59 发布