在软件系统中,有时候我们会使用继承来扩展对象的功能,但是由于继承为类型引入的静态特质,使得这种扩展方式缺乏灵活性;并且随着子类的增多(扩展功能的增多),各种子类的组合(扩展功能的组合)会导致更多子类的膨胀。如何使“对象功能的扩展”能够根据需要来动态地实现?同时避免“扩展功能的增多”带来的子类膨胀问题?从而使得任何“功能扩展变化”所导致的影响将为最低?这就是本文要讲的Decorator模式。
装饰模式(Decorator Pattern)也叫包装器模式(Wrapper Pattern)。GoF在《设计模式》一书中给出的定义为:动态地给一个对象添加一些额外的职责。换而言之,装饰类为子类扩展新功能提供了一种灵活的替换机制。
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
Person me = new Person("Xufei96");
RunningPerson run = new RunningPerson();
UnFlyingPerson unfly = new UnFlyingPerson();
run.GetPersonInstance(me);
unfly.GetPersonInstance(run);
unfly.Show();
Console.ReadKey();
}
}
class Person
{
public Person(string name)
{
Name = name;
}
public Person()
{
}
protected string Name { get; set; }
protected Person PersonInstance { get; set; }
public void GetPersonInstance(Person currentPerson)
{
PersonInstance = currentPerson;
}
public virtual void Show()
{
if (PersonInstance != null)
{
PersonInstance.Show();
}
else
{
Console.WriteLine("The person's name is {0}~", Name);
}
}
}
class RunningPerson : Person
{
public override void Show()
{
base.Show();
Console.WriteLine("I can run, I'm a running man~");
}
}
class FlyingPerson : Person
{
public override void Show()
{
base.Show();
Console.WriteLine("I can fly, I'm a bird man~");
}
}
class UnRunningPerson : Person
{
public override void Show()
{
base.Show();
Console.WriteLine("I can't run, I'm not a running man~");
}
}
class UnFlyingPerson : Person
{
public override void Show()
{
base.Show();
Console.WriteLine("I can't fly, I'm not a bird man~");
}
}
}
codes were familiar with 《大话设计模式》。