Java设计模式中装饰器模式(套娃)

装饰器模式是一种结构型设计模式,它允许你在不改变对象自身的情况下动态地给对象添加新的功能。这种模式通过将对象放入装饰器对象中,然后将装饰器对象包装在其他装饰器对象中,以实现各种功能的组合。这种模式符合开放封闭原则,即对扩展是开放的,对修改是封闭的。

以下是装饰器模式的一般结构:

  1. Component(组件):定义了一个对象接口,可以给这些对象动态地添加功能。

  2. ConcreteComponent(具体组件):实现了Component接口的具体对象。

  3. Decorator(装饰器):持有一个Component对象的引用,并定义一个与Component接口一致的接口。

  4. ConcreteDecorator(具体装饰器):实现了Decorator接口的具体装饰器,负责给Component对象添加新的功能。

下面是一个简单的Java示例,演示了如何使用装饰器模式:

// 1. Component
interface Coffee {
    double getCost();
    String getDescription();
}

// 2. ConcreteComponent
class SimpleCoffee implements Coffee {
    @Override
    public double getCost() {
        return 1.0;
    }
    
    @Override
    public String getDescription() {
        return "Coffee";
    }
}

// 3. Decorator
abstract class CoffeeDecorator implements Coffee {
    protected Coffee decoratedCoffee;

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

    public double getCost() {
        return decoratedCoffee.getCost();
    }

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

// 4. ConcreteDecorator
class MilkDecorator extends CoffeeDecorator {
    public MilkDecorator(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }

    public double getCost() {
        return super.getCost() + 0.5;
    }

    public String getDescription() {
        return super.getDescription() + ", Milk";
    }
}

// 5. 使用示例
public class Main {
    public static void main(String[] args) {
        // 制作一杯简单咖啡
        Coffee simpleCoffee = new SimpleCoffee();
        System.out.println("Cost: " + simpleCoffee.getCost() + ", Description: " + simpleCoffee.getDescription());

        // 给简单咖啡加入牛奶
        Coffee milkCoffee = new MilkDecorator(simpleCoffee);
        System.out.println("Cost: " + milkCoffee.getCost() + ", Description: " + milkCoffee.getDescription());
    }
}

在这个示例中,SimpleCoffee是具体组件,MilkDecorator是具体装饰器。我们可以动态地给简单咖啡添加额外的功能,比如牛奶。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rsun04551

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值