分析详见:http://lvxingzhelimin.blog.163.com/blog/static/1707165502011101035413741/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person xc = new Person("小菜");
Console.WriteLine("\n第一种装扮:");
TShirts dtx = new TShirts();
BigTrouser kk = new BigTrouser();
Sneaker pqx = new Sneaker();
//具体装饰类继承了服饰类,服饰类继承了人类,所以具体装饰类也就继承了人类,
//因此,具体装饰类就可以替换人类,这样装饰顺序就产生了不同的装饰风格。
//里氏代换原则/依赖倒转原则
pqx.Decorate(xc);
kk.Decorate(pqx);
dtx.Decorate(kk );
dtx.Show();
Console.Read();
}
}
}
//Person类(ConcreteComponent)
class Person
{
public Person()
{ }
//人的姓名
private string name;
public Person(string name)
{
this.name = name;
}
//装扮的对象描述
public virtual void Show()
{
Console.WriteLine("装饰的{0}",name );
}
}
//服饰类(Decorator):Person这个类没有必要知道Finery类的存在,Finery类的作用是对Person的功能的扩展
class Finery : Person
{
protected Person component;
//定义打扮的对象
public void Decorate(Person component)
{
this.component = component;
}
//显示打扮的对象,重写父类(Person)方法
public override void Show()
{
if (component != null)
{
component.Show();
}
}
}
//具体服饰类(ConcreteDecorator)
class TShirts : Finery
{
public override void Show()
{
Console.WriteLine("大T恤");
base.Show();
}
}
class BigTrouser : Finery
{
public override void Show()
{
Console.WriteLine("垮裤");
base.Show();
}
}
class Sneaker : Finery
{
public override void Show()
{
Console.WriteLine("破球鞋");
base.Show();
}
}
class LeatherShoes : Finery
{
public override void Show()
{
Console.WriteLine("皮鞋");
base.Show();
}
}