装饰模式:动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
一、特点:
是为已有功能动态添加更多功能的一种方式。
把类中的装饰功能从类中搬移去除,可以简化原有的类
二、优点:
有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑
三、应用:
当系统需要新功能的时候,是向旧的类中添加新的代码,这些新添加的代码通常装饰了原有类的核心职责或主要行为
1.需要扩展一个类的功能,或给一个类追加附加功能。
2.需要动态地给一个对象增加功能,这就区别于继承机制(静态的)。
3.需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不那么现实
装饰模式就如QQ厘米秀似的,可以给它添加衣服,饰品
下面来看看装饰过程吧
class Program
{
static void Main(string[] args)
{
Person xc = new Person("千千");
Console.WriteLine("\n第一种装扮"); //换行
Sneakers pqx = new Sneakers();
BigTrouser kk = new BigTrouser();
Tshirts dtx = new Tshirts();
pqx.Decorate(xc);
kk.Decorate(pqx);
dtx.Decorate(kk);
dtx.Show();
Console.WriteLine("\n第二种装扮");
LeatherShoes px = new LeatherShoes();
Tie ld = new Tie();
Suit xz = new Suit();
px.Decorate(xc);
ld.Decorate(px);
xz.Decorate(ld);
xz.Show();
Console.Read();
}
}
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() //重写Person中的Show方法
{
if (component !=null )
{
component.Show();
}
}
}
//具体服饰类
class Tshirts : Finery
{
public override void Show()
{
Console.Write("T恤");
base.Show(); //派生类调用父类中的方法
}
}
class BigTrouser : Finery
{
public override void Show()
{
Console.Write("垮裤");
base.Show();
}
}
class Sneakers : Finery
{
public override void Show()
{
Console.WriteLine("球鞋");
base.Show();
}
}
哈哈,有没有感觉特别好玩儿。