装饰器模式
装饰器模式是一种结构型设计模式,它允许向一个对象动态地添加新功能,同时不改变其接口。这种模式是通过创建一个包装器,即装饰器,来包裹原始对象,从而为其添加新的行为或责任。
功能
**动态添加功能:**允许向对象添加新的功能,而无需修改现有代码。
**保持接口一致性:**装饰器和被装饰对象具有相同的接口,因此客户端无需知道对象是否被装饰。
优点:
**灵活性:**可以动态地添加或删除功能,而无需修改现有代码。
**遵循开放-关闭原则:**允许扩展功能而不修改现有代码,符合设计原则。
**单一职责原则:**每个装饰器负责一个特定的责任,使得代码更加清晰和易于维护
代码示例
Coffee 表示一杯咖啡,我们想要向这个咖啡添加额外的装饰,比如加糖、加奶。我们可以使用装饰器模式来实现:
- 代码:
using System;
// 基础组件:咖啡
interface ICoffee
{
double Cost();
}
// 咖啡类:实现基础组件接口
class Coffee : ICoffee
{
public double Cost()
{
return 10;
}
}
// 装饰器抽象类
abstract class CoffeeDecorator : ICoffee
{
protected ICoffee coffee;
public CoffeeDecorator(ICoffee coffee)
{
this.coffee = coffee;
}
public virtual double Cost()
{
return coffee.Cost();
}
}
// 装饰器:加糖
class SugarDecorator : CoffeeDecorator
{
public SugarDecorator(ICoffee coffee) : base(coffee) { }
public override double Cost()
{
return base.Cost() + 5;
}
}
// 装饰器:加奶
class MilkDecorator : CoffeeDecorator
{
public MilkDecorator(ICoffee coffee) : base(coffee) { }
public override double Cost()
{
return base.Cost() + 7;
}
}
class Program
{
static void Main(string[] args)
{
// 使用装饰器
ICoffee coffee = new Coffee();
Console.WriteLine("原始咖啡价格: " + coffee.Cost());
ICoffee coffeeWithSugar = new SugarDecorator(coffee);
Console.WriteLine("加糖咖啡价格: " + coffeeWithSugar.Cost());
ICoffee coffeeWithMilk = new MilkDecorator(coffee);
Console.WriteLine("加奶咖啡价格: " + coffeeWithMilk.Cost());
ICoffee coffeeWithSugarAndMilk = new MilkDecorator(new SugarDecorator(coffee));
Console.WriteLine("加糖和奶咖啡价格: " + coffeeWithSugarAndMilk.Cost());
}
}