【设计模式|结构型】装饰器模式(Decorator Pattern)

背景

假设你有一个咖啡店,你的基本咖啡是黑咖啡。然而,你希望能够为客户提供添加额外配料(如牛奶、糖、巧克力等)的选项,而不需要为每种配料创建一个新的咖啡类。

这时,你可以使用装饰器模式来实现。

概述

装饰器模式(Decorator Pattern)是一种结构型设计模式,它允许你在不改变现有对象结构的情况下,动态地将行为添加到对象中。通过将对象包装在具有相同父类或实现相同接口的装饰器类中,可以逐层地为对象添加功能。

代码示例

定义一个基本的咖啡接口 Coffee

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

创建一个具体的黑咖啡类 BlackCoffee 实现 Coffee 接口:

public class BlackCoffee implements Coffee {
    @Override
    public String getDescription() {
        return "Black Coffee";
    }

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

定义一个装饰器接口 CoffeeDecorator,表示咖啡的配料:

public interface CoffeeDecorator extends Coffee {
}

创建具体的装饰器类来实现 CoffeeDecorator 接口,例如牛奶装饰器类 MilkDecorator

public class MilkDecorator implements CoffeeDecorator {
    private Coffee coffee;

    public MilkDecorator(Coffee coffee) {
        this.coffee = coffee;
    }

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

    @Override
    public double getCost() {
        return coffee.getCost() + 1.0;
    }
}

同样,可以创建其他的装饰器类,例如糖装饰器类 SugarDecorator

public class SugarDecorator implements CoffeeDecorator {
    private Coffee coffee;

    public SugarDecorator(Coffee coffee) {
        this.coffee = coffee;
    }

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

    @Override
    public double getCost() {
        return coffee.getCost() + 0.5;
    }
}

在客户端代码中使用装饰器模式来创建不同的咖啡对象:

public class Main {
    public static void main(String[] args) {
        // 创建一个黑咖啡对象
        Coffee blackCoffee = new BlackCoffee();
        System.out.println(blackCoffee.getDescription() + " - $" + blackCoffee.getCost());

        // 创建一个加了牛奶的咖啡对象
        Coffee milkCoffee = new MilkDecorator(blackCoffee);
        System.out.println(milkCoffee.getDescription() + " - $" + milkCoffee.getCost());

        // 创建一个既加了牛奶又加了糖的咖啡对象
        Coffee milkSugarCoffee = new SugarDecorator(milkCoffee);
        System.out.println(milkSugarCoffee.getDescription() + " - $" + milkSugarCoffee.getCost());
    }
}

输出结果:

Black Coffee - $2.0
Black Coffee, Milk - $3.0
Black Coffee, Milk, Sugar - $3.5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值