装饰模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
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()
{
component.show();
}
}
class TShirts : Finery
{
public override void show()
{
Console.WriteLine("大T恤");
base.show();
}
}
class BigTrouser : Finery
{
public override void show()
{
Console.WriteLine("垮裤");
base.show();
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("begin");
Person xc = new Person("贾");
Console.WriteLine("the first");
TShirts ts = new TShirts();
BigTrouser bi = new BigTrouser();
ts.Decorate(xc); //装饰原有类,其实就是父类指向了之类,增加了功能
bi.Decorate(ts);
bi.show();
}
}
装饰模式提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象 ,因此
当需要执行特殊行为时,客户代码就可以在运行时根据需要,选择,按顺序的使用装饰功能包装对象了。
这样做的好处,有效的把类的核心功能和装饰功能区分开,而且还可以消除相关类中重复的装饰逻辑。
装饰模式的特点: