Java设计模式之装饰器模式。

装饰器模式(Decorator Pattern)是Java开发中常用的设计模式之一,属于结构型设计模式,它允许向对象动态添加新功能,同时又不改变其结构。装饰器模式通过创建包装对象,即装饰器,来包裹原始对象,并在不改变原始对象的基础上,动态地添加新的行为或功能,下面用Java代码来看看它的使用方法吧。

// 抽象组件接口
interface Beverage {
    String getDescription();
    double cost();
}

// 具体组件类:咖啡
class Coffee implements Beverage {
    @Override
    public String getDescription() {
        return "Coffee";
    }

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

// 抽象装饰器类
abstract class CondimentDecorator implements Beverage {
    protected Beverage beverage;

    public CondimentDecorator(Beverage beverage) {
        this.beverage = beverage;
    }
}

// 具体装饰器类:牛奶
class Milk extends CondimentDecorator {
    public Milk(Beverage beverage) {
        super(beverage);
    }

    @Override
    public String getDescription() {
        return beverage.getDescription() + ", Milk";
    }

    @Override
    public double cost() {
        return beverage.cost() + 0.5;
    }
}

// 具体装饰器类:糖
class Sugar extends CondimentDecorator {
    public Sugar(Beverage beverage) {
        super(beverage);
    }

    @Override
    public String getDescription() {
        return beverage.getDescription() + ", Sugar";
    }

    @Override
    public double cost() {
        return beverage.cost() + 0.3;
    }
}

// 测试代码
public class DecoratorPatternExample {
    public static void main(String[] args) {
        Beverage coffee = new Coffee();
        System.out.println("Description: " + coffee.getDescription() + ", Cost: " + coffee.cost());

        Beverage coffeeWithMilk = new Milk(coffee);
        System.out.println("Description: " + coffeeWithMilk.getDescription() + ", Cost: " + coffeeWithMilk.cost());

        Beverage coffeeWithMilkAndSugar = new Sugar(coffeeWithMilk);
        System.out.println("Description: " + coffeeWithMilkAndSugar.getDescription() + ", Cost: " + coffeeWithMilkAndSugar.cost());
    }
}

优点:

  • 装饰器模式可以动态地添加额外的功能,而无需修改现有代码。
  • 可以避免使用子类对功能进行扩展,避免类爆炸问题。
  • 支持递归嵌套装饰器,灵活性高。

缺点:

  • 可能会导致设计中出现大量的装饰器类,增加复杂度。

使用场景:

  • 当需要动态地为对象添加额外的功能时,可以使用装饰器模式。
  • 不希望使用子类来扩展功能时,可以考虑使用装饰器模式。
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值