23种设计模式-结构型模式之装饰器模式(Java版本)

Java 装饰器模式(Decorator Pattern)详解

🎁 什么是装饰器模式?

装饰器模式是一种结构型设计模式,允许向一个对象动态添加新的功能,而不改变其结构。

🧱 你可以想象成在原有功能上“包裹”一层新功能,就像“套娃”或者“包礼物”。


🧠 使用场景

  • 需要在不修改类的情况下,扩展其功能
  • 需要动态地为对象添加功能
  • 多个类只有少量差异时,使用继承会导致类爆炸

🏗️ 模式结构

  • Component(抽象构件):定义对象接口
  • ConcreteComponent(具体构件):被装饰的原始对象
  • Decorator(装饰器抽象类):持有组件对象的引用,扩展功能
  • ConcreteDecorator(具体装饰器):实现具体增强功能

✅ 示例:咖啡加配料

抽象组件

public interface Coffee {
    String getDescription();
    double cost();
}

具体组件

public class SimpleCoffee implements Coffee {
    @Override
    public String getDescription() {
        return "普通咖啡";
    }

    @Override
    public double cost() {
        return 5.0;
    }
}

抽象装饰器

public abstract class CoffeeDecorator implements Coffee {
    protected Coffee decoratedCoffee;

    public CoffeeDecorator(Coffee coffee) {
        this.decoratedCoffee = coffee;
    }

    @Override
    public String getDescription() {
        return decoratedCoffee.getDescription();
    }

    @Override
    public double cost() {
        return decoratedCoffee.cost();
    }
}

具体装饰器:加牛奶

public class MilkDecorator extends CoffeeDecorator {
    public MilkDecorator(Coffee coffee) {
        super(coffee);
    }

    @Override
    public String getDescription() {
        return super.getDescription() + " + 牛奶";
    }

    @Override
    public double cost() {
        return super.cost() + 2.0;
    }
}

具体装饰器:加糖

public class SugarDecorator extends CoffeeDecorator {
    public SugarDecorator(Coffee coffee) {
        super(coffee);
    }

    @Override
    public String getDescription() {
        return super.getDescription() + " + 糖";
    }

    @Override
    public double cost() {
        return super.cost() + 1.0;
    }
}

客户端使用

public class Main {
    public static void main(String[] args) {
        Coffee coffee = new SimpleCoffee();
        coffee = new MilkDecorator(coffee);
        coffee = new SugarDecorator(coffee);
        System.out.println(coffee.getDescription() + ",价格:" + coffee.cost());
    }
}

🧩 优点

  • 灵活、可扩展性强,支持动态组合
  • 避免类继承造成的类爆炸
  • 满足开闭原则

⚠️ 缺点

  • 多层装饰器会增加系统复杂度,调试不易
  • 对象结构可能过于复杂,难以理解

✅ 使用建议

  • 当你希望在运行时增加对象行为,而不是通过继承
  • 多个类之间功能相似,可通过组合代替继承
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值