装饰器模式

博客以咖啡点餐为例,介绍了装饰器模式的基础实现。默认点餐逻辑只能得到基础咖啡,若对口味不满意,可通过装饰器为咖啡加糖。总结指出,装饰器模式是对已有对象功能不满意时,用装饰器进行功能添加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基础实现

public interface Coffee {
    public void printMaterial();
}

一个苦咖啡的实现

public class BitterCoffee implements Coffee {
    @Override
    public void printMaterial() {
        System.out.println("咖啡");
    }

默认的点餐逻辑

public static void main(String[] args) {
        Coffee coffee = new BitterCoffee();
        coffee.printMaterial();
    }

此时就是默认的一个实现,只能是最基础的咖啡

我发现口味不对,需要加糖

public class SugerCoffee implements Coffee {
    private final Coffee coffee;
    public SugerCoffee (Coffee coffee){
        this.coffee = coffee;
    }

    @Override
    public void printMaterial() {
        System.out.println("加糖");
        coffee.printMaterial();
    }
}

此时就可以对我原先的那杯咖啡进行加糖

 public static void main(String[] args) {
        Coffee coffee = new BitterCoffee();//原先那杯苦咖啡
        
        coffee = new SugerCoffee(coffee);
        coffee.printMaterial();
    }

确实实现了加糖的功能

需要注意这两行代码

Coffee coffee = new BitterCoffee();

coffee = new SugerCoffee(coffee);

稍微总结一下,装饰器模式,就是我已经有了有了一个对象,但是对这个对象的功能不是很满意,我就拿装饰器给他装饰一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值