您的位置:首页 > 其它

装饰模式 -- 大话设计模式

2015-10-29 10:09 127 查看
在今天,读书有时是件“麻烦”事。它需要你付出时间,付出精力,还要付出一份心境。--仅以《大话设计模式》来祭奠那逝去的……

装饰模式:动态的给一个对象增加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活(适合场景,需要经常动态的添加额外职责的时候使用。稳定的业务不建议使用装饰模式,增加不必要的代码量)

1.装扮小游戏

  给要出门的小伙子打扮一下,衣服都在衣橱里面,挑选一下打扮起来

  首先建立一个人物模型Person

public class Person
{
public Person() { }

private string _name;

public Person(string name)
{
this._name = name;
}

public virtual void Show()
{
Console.WriteLine("装扮的{0}", _name);
}
}


  其次定义一个装饰类,装饰类要继承人物模型类,将人物模型内置到装饰类中,方便装饰处理

public class Finery : Person
{
protected Person _component;

public void Decorate(Person person)
{
this._component = person;
}

public override void Show()
{
if (_component != null)
_component.Show();
}
}


  定义各种服饰类,继承装饰类,实现装饰人物模型的功能

public class TShirts : Finery
{
public override void Show()
{
Console.Write("大T恤 ");
base.Show();
}
}

public class BigTrouser : Finery
{
public override void Show()
{
Console.Write("垮裤 ");
base.Show();
}
}


  开始装饰人物模型,实例化一个模型“小张”,首先给小张穿上垮裤,然后是T恤,就可以出门了(装饰模式是一个链式调取方式,由外到内或者是由下到上

static void Main(string[] args)
{
//装饰模式
Person person = new Person("小张");

//再穿一个大T恤
TShirts dtx = new TShirts();
dtx.Decorate(person);

//先穿一个垮裤
BigTrouser kk = new BigTrouser();
kk.Decorate(dtx);

//可以出门了
kk.Show();
}


  来看看帅帅的小张吧

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: