定义
装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就添加功能来说,装饰模式比生成子类更加灵活。
结构图
分析
装饰模式是利用Operation来对对象进行包装。这样每个装饰对象的实现和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当众。
如果只有一个ConcreteComponet类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。
代码实例
为张三进行装扮,上身T恤衫,下身牛仔裤,鞋子是球鞋。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
class Person
{
public Person() { }
private string name;
public Person(string name)
{
this.name = name;
}
public virtual void Show()
{
Console.WriteLine("装扮的{0}", name);
}
}
class Finery : Person
{
protected Person component;
public void Decorate(Person component)
{
this.component = component;
}
public override void Show()
{
if (component != null)
{
component.Show();
}
}
}
class Tshirt : Finery
{
public override void Show()
{
Console.Write("T恤衫 ");
base.Show();
}
}
class Qiuxie : Finery
{
public override void Show()
{
Console.Write("球鞋 ");
base.Show();
}
}
class Niuzaiku : Finery
{
public override void Show()
{
Console.Write("牛仔裤 ");
base.Show();
}
}
class Program
{
static void Main(string[] args)
{
Person ps = new Person("张三");
Tshirt tshirt = new Tshirt();
Qiuxie qx = new Qiuxie();
Niuzaiku nzk = new Niuzaiku();
tshirt.Decorate(ps);
qx.Decorate(tshirt);
nzk.Decorate(qx);
nzk.Show();
Console.ReadLine();
}
}
}
每个show结束后,都会运行上一层的show。此处的show即为要添加的方法。