装饰模式:动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
这次直接上代码在进行解释吧(类图什么的太麻烦了,所以就不做了)。
抽象人
/// <summary> /// 抽象人 /// </summary> public abstract class AbsPerson { public abstract void Write(); }
需要被装饰的人:实现抽象人,重写需要执行的操作。
/// <summary> /// 需要装饰的人 /// </summary> public class Person : AbsPerson { public string Name { get; set; } public Person(string name) { this.Name = name; } public override void Write() { Console.WriteLine($"{Name}现在什么都没穿哦!"); } }
抽象装饰类:同样也继承了抽象人,一个AbsPerson字段表示需要被装饰的对象,用SetComponent方法进行赋值,我觉得这个对象是装饰模式的关键。
/// <summary> /// 抽象装饰 /// </summary> public abstract class PersonDecorate : AbsPerson { public AbsPerson person; public void SetComponent(AbsPerson p) { this.person = p; } public override void Write() { if (person != null) { person.Write(); } } }
具体装饰类:base.Write() 与上面 person.Write()应该结合起来理解,最好就是一步一步调试跟踪。
/// <summary> /// 具体装饰一 /// </summary> public class DecorateClothes : PersonDecorate { public override void Write() { base.Write(); Console.WriteLine("穿上帅气的衣服!"); } } /// <summary> /// 具体装饰二 /// </summary> public class DecorateShoe : PersonDecorate { public override void Write() { base.Write(); Console.WriteLine("穿上增高的鞋子!"); } }
测试程序:
/// <summary> /// 执行程序 /// </summary> /// <param name="args"></param> static void Main(string[] args) { var person = new Person("张三"); var decorate1 = new DecorateClothes(); var decorate2 = new DecorateShoe(); decorate1.SetComponent(person); decorate2.SetComponent(decorate1); decorate2.Write(); Console.ReadKey(); }
先分别创建装饰对象与被装饰的对象,接着将person放入装饰一中,因为装饰一 也是继承的AbsPerson,接着把装饰一放入装饰二中(好像连缀,返回的对象本身可以继续调用,这里就是把这个对象拿来一直附加其他东西)。代码简单,最好呢 还是跟踪理解。