Java设计模式-装饰者模式

文章目录

10、装饰者模式

装饰者模式:动态的将新功能附加到对象上。体现了开闭原则。

应用场景:咖啡店里有深焙咖啡、浓缩咖啡。咖啡可以加的调料有巧克力调料、奶泡调料。装饰者类图如下:

在这里插入图片描述

代码:

public abstract class Coffee {
    protected String description;
    protected Integer price;

    public abstract String getDescription();
    public abstract Integer cost();

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }
}

//深焙咖啡
public class DarkRoast extends Coffee {

    public DarkRoast(){
        setPrice(3);
        setDescription("深焙咖啡");
    }

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public Integer cost() {
        return price;
    }
}

//浓缩咖啡
public class Espresso extends Coffee{
    public Espresso(){
        setPrice(5);
        setDescription("浓缩咖啡");
    }

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public Integer cost() {
        return getPrice();
    }
}

//调料抽象类
public abstract class Decorator extends Coffee{
    protected Coffee coffee;
}

//奶泡调料
public class Whip extends Decorator {

    public Whip(Coffee coffee){
        this.coffee = coffee;
        setPrice(1);
    }

    @Override
    public String getDescription() {
        return coffee.getDescription()+",奶泡调料";
    }

    @Override
    public Integer cost() {
        return coffee.cost()+getPrice();
    }
}

//巧克力调料
public class Chocolate extends Decorator {

    public Chocolate(Coffee coffee){
        this.coffee = coffee;
        setPrice(2);
    }

    @Override
    public String getDescription() {
        return coffee.getDescription()+",巧克力调料";
    }

    @Override
    public Integer cost() {
        return coffee.cost()+getPrice();
    }
}

//测试
public class Test42 {
    public static void main(String[] args) {
        Coffee order = new DarkRoast();
        order = new Whip(order);
        order = new Chocolate(order);
        System.out.println(order.getDescription()+" 共"+order.cost()+"元");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值