装饰模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
class Person
{
public Person()
{
}
private string name;
public Person(string name)
{
this.name = name;
}
public virtual void Show()
{
Console.WriteLine("装扮的{0}",name);
}
}
/// <summary>
/// 服饰父类
/// </summary>
class Finery : Person
{
protected Person Component;
//打扮
public void Decorate(Person component)
{
Component = component;
}
public override void Show()
{
if(Component != null)
Component.Show();
}
}
/// <summary>
/// 大垮裤
/// </summary>
class BigTrouser : Finery
{
public override void Show()
{
Console.Write(" 大垮裤 ");
base.Show();
}
}
/// <summary>
/// T恤
/// </summary>
class TShirts : Finery
{
public override void Show()
{
Console.Write(" 大T恤 ");
base.Show();
}
}
/// <summary>
/// 破球鞋
/// </summary>
class WearSneakers : Finery
{
public override void Show()
{
Console.Write(" 破球鞋 ");
base.Show();
}
}
/// <summary>
/// 西装
/// </summary>
class WearSuit : Finery
{
public override void Show()
{
Console.Write(" 西装 ");
base.Show();
}
}
/// <summary>
/// 方法主体
/// </summary>
class Program
{
static void Main(string[] args)
{
//个人理解:这里的装饰就是考虑重写方法调用时从子类到父类都会依次调用
var xc = new Person("张三");
Console.WriteLine("\n第一种装扮:");
var ws = new WearSneakers();
var bt = new BigTrouser();
ws.Decorate(xc);
bt.Decorate(ws);
bt.Show();
Console.ReadLine();
}
}
运行结果: