装饰模式是为已有功能动态的添加更多功能的一种方式。
当系统需要新功能的时候,是向旧的类中添加新的代码,而这些新的代码通常装饰了原有类的核心职责或者主要行为, 这些新的逻辑增加了主类的复杂度,但是它们仅仅是满足一些只在某这特定情况下才会执行的特殊行为的需要,且先后执行顺序不确定。 这样,每个要装饰的功放在单独的类中,并设置这个类需要装饰的对象,当需要执行特殊行为时,客户端代码就可以在运行时根据需要,有选择按顺序的使用装饰功能包装的对象了。
装饰模式的优点是把类中的装饰功能从类中搬移出去,简化了原有的类,并把核心功能和装饰功能区分开来。
使用装饰模式实现给人穿衣服的例子:
首先定义被装饰类:
/// <summary>
/// 装饰类与被装饰类的接口,定义了被装饰对象和装饰类的职责
/// </summary>
public interface IComponent
{
void Show();
}
/// <summary>
/// 被装饰的类
/// </summary>
public class Person:IComponent
{
private string name;
public Person(string name)
{
this.name = name;
}
/// <summary>
/// 核心功能
/// </summary>
public virtual void Show()
{
Console.WriteLine("Name: {0}", name);
}
}
定义装饰类:
/// <summary>
/// 装饰类的基类,设置需要装饰的对象,并提供调用被装饰类的核心功能的方法
/// </summary>
public class Decorator:IComponent
{
protected IComponent component;
public Decorator(IComponent component)
{
this.component = component;
}
public virtual void Show()
{
if (component!=null)
{
component.Show();
}
}
}
/// <summary>
/// 装饰类的实现,在调用被装饰对象的核心方法后,又执行被装饰类中的其它功能,即装饰功能
/// </summary>
public class TshirtDecorator : Decorator
{
public TshirtDecorator(IComponent component)
: base(component)
{
}
public override void Show()
{
base.Show();
Console.WriteLine("Put on TShirt");
}
}
public class TrouserDecorator : Decorator
{
public TrouserDecorator(IComponent component)
: base(component)
{
}
public override void Show()
{
base.Show();
Console.WriteLine("Put on Trouser");
}
}
public class ShoesDecorator : Decorator
{
public ShoesDecorator(IComponent component)
: base(component)
{
}
public override void Show()
{
base.Show();
Console.WriteLine("Put on Shoes");
}
}
使用装饰类实现装饰功能
Person kelly = new Person("Kelly");
TshirtDecorator tshirt = new TshirtDecorator(kelly);
TrouserDecorator trouser = new TrouserDecorator(tshirt);
ShoesDecorator shoes = new ShoesDecorator(trouser);
shoes.Show();
运行结果为:
Name: Kelly
Put on TShirt
Put on Trouser
Put on Shoes