首页 > 代码库 > 设计模式笔记4 装饰模式
设计模式笔记4 装饰模式
1.1 定义
动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
1.2 类图
1.3 代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 装饰模式 8 { 9 class Person10 {11 private string name;12 public Person() { }13 public Person(string name)14 {15 this.name = name;16 }17 18 public virtual void Show()19 {20 Console.WriteLine("装扮的{0}", this.name);21 }22 }23 // 服饰类24 class Finery : Person25 {26 protected Person component;27 28 // 打扮29 public void Decorate(Person component)30 {31 this.component = component;32 }33 34 public override void Show()35 {36 if (component!=null)37 {38 component.Show();39 }40 }41 42 43 44 }45 46 // 具体服饰类47 class TShirt : Finery48 {49 public override void Show()50 {51 Console.WriteLine("大T恤");52 base.Show();53 } 54 }55 56 // 牛仔裤57 class Jeans : Finery58 {59 public override void Show()60 {61 Console.WriteLine("牛仔裤");62 base.Show();63 }64 }65 66 67 class Shoes : Finery68 {69 public override void Show()70 {71 Console.WriteLine("破球鞋");72 base.Show();73 }74 }75 76 }
调用
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 装饰模式 8 { 9 class Program10 {11 static void Main(string[] args)12 {13 Person p = new Person("大头");14 15 16 TShirt t = new TShirt();17 Jeans j = new Jeans();18 Shoes s = new Shoes();19 20 t.Decorate(p);21 j.Decorate(t);22 s.Decorate(j);23 24 s.Show();25 26 }27 }28 }
1.4 总结
装饰模式就是为已有功能动态地添加更多功能的一种方式。
当我们系统需要更新功能时,给原有的类添加装饰模式,就可以给主类添加新的方法和字段。
设计模式笔记4 装饰模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。