装饰器模式例子

一、装饰器模式

动态地给一个对象添加一些额外的职责,同时不改变其结构。常用于动态地为对象添加功能,避免使用继承导致的类爆炸问题。

二、例子

using System;

// 原始组件:咖啡类
public class Coffee
{
    public virtual decimal Cost()
    {
        return 5;
    }
}

// 装饰器基类
public abstract class CoffeeDecorator : Coffee
{
    protected Coffee _coffee;

    public CoffeeDecorator(Coffee coffee)
    {
        _coffee = coffee;
    }
}

// 具体装饰器:牛奶
public class MilkDecorator : CoffeeDecorator
{
    public MilkDecorator(Coffee coffee) : base(coffee)
    {
    }

    public override decimal Cost()
    {
        return _coffee.Cost() + 2;
    }
}

// 具体装饰器:糖
public class SugarDecorator : CoffeeDecorator
{
    public SugarDecorator(Coffee coffee) : base(coffee)
    {
    }

    public override decimal Cost()
    {
        return _coffee.Cost() + 1;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 创建一个原始的咖啡对象
        Coffee simpleCoffee = new Coffee();
        Console.WriteLine("Cost of simple coffee: " + simpleCoffee.Cost());  // Output: Cost of simple coffee: 5

        // 使用装饰器为咖啡添加牛奶和糖
        Coffee milkCoffee = new MilkDecorator(simpleCoffee);
        Coffee sugarMilkCoffee = new SugarDecorator(milkCoffee);
        Console.WriteLine("Cost of milk and sugar coffee: " + sugarMilkCoffee.Cost());  // Output: Cost of milk and sugar coffee: 8
    }
}


总结

在这个示例中,Coffee 是一个基础组件,CoffeeDecorator 是装饰器的基类,MilkDecorator 和 SugarDecorator 是具体的装饰器。通过将装饰器叠加在基础组件上,我们可以为咖啡添加不同的调料,并且调料可以按照需要组合在一起。

这个示例展示了装饰器模式的基本思想,即通过创建装饰器类,将原始对象作为参数传递,并在装饰器类中扩展对象的功能。这样可以在不修改原始对象代码的情况下,动态地为对象添加新的功能。。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Kevin__ZHENG

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

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

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

打赏作者

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

抵扣说明:

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

余额充值