(C#)设计模式之装饰模式

1.装饰模式
  动态的给一个对象添加一些额外的职责,就添加功能来说,装饰模式比生成子类更加灵活。
*装饰模式是为已有功能动态添加更多功能的一种方式。
*装饰模式将原有类中的核心职责与装饰功能分离。简化了原有的类即去除类重复的装饰逻辑。
*装饰模式将每个装饰功能放在单独的类中并让这个类装饰它所要装饰的对象。


namespace 设计模式 { class Program { static void Main(string[] args) { Person 刘德华 = new Person("刘德华"); Console.WriteLine("开始装扮"); Tshirt tshirt = new Tshirt(); Jonson jonson = new Jonson(); Shose shose = new Shose();
//层层包装,不断向原有的类中添加新的装饰物 tshirt.Decrator(刘德华); jonson.Decrator(tshirt); shose.Decrator(jonson); shose.Show(); } } /// <summary> /// 具体的需要被装饰的类,也是需要丰富功能的类 /// </summary> 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 Decrator(Person component) { this.component = component; } public override void Show() { if (component!=null) { component.Show(); } } } /// <summary> /// 具体的服饰类 /// </summary> class Tshirt:Finery { public override void Show() { Console.WriteLine("T恤"); base.Show(); } } class Jonson : Finery { public override void Show() { Console.WriteLine("牛仔裤"); base.Show(); } } class Shose : Finery { public override void Show() { Console.WriteLine("牛皮鞋"); base.Show(); } } }

*先将各个功能层层加载在一起,然后由最上层的实例调用内部功能并依据基类base的方法将功能层层展开。

  

posted @ 2015-08-04 11:08  世纪末の魔术师  阅读(353)  评论(0编辑  收藏  举报