一、装饰器模式
动态地给一个对象添加一些额外的职责,同时不改变其结构。常用于动态地为对象添加功能,避免使用继承导致的类爆炸问题。
二、例子
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 是具体的装饰器。通过将装饰器叠加在基础组件上,我们可以为咖啡添加不同的调料,并且调料可以按照需要组合在一起。
这个示例展示了装饰器模式的基本思想,即通过创建装饰器类,将原始对象作为参数传递,并在装饰器类中扩展对象的功能。这样可以在不修改原始对象代码的情况下,动态地为对象添加新的功能。。