// See https://aka.ms/new-console-template for more information /* * 个人理解 你要往原有的东西上加东西 Phone=装饰手机原材料 Decorator=装饰手机中间人 XiaoMi=具体装饰的手机 Sticker=装饰手机中间人拿装饰手机原材料来装饰XiaoMi。给它贴膜 */ //拿出小米手机 Phone phone1 = new XiaoMi(); Decorator xiaoMiSticker = new Sticker(phone1); xiaoMiSticker.Print(); Decorator xiaoMiAccessories = new Accessories(phone1); xiaoMiAccessories.Print(); /// <summary> /// 手机抽象类,即装饰者模式中的抽象组件类 /// </summary> public abstract class Phone { public abstract void Print(); } /// <summary> /// 装饰类 /// </summary> public abstract class Decorator : Phone { private Phone Phone; protected Decorator(Phone phone) { Phone = phone; } public override void Print() { if (Phone != null) Console.WriteLine("我是Decorator重写实现"); Phone?.Print(); } } /// <summary> /// 小米手机,即装饰着模式中的具体组件类 /// </summary> public class XiaoMi : Phone { /// <summary> /// 重写基类方法 /// </summary> public override void Print() { Console.WriteLine("开始执行具体对象-小米手机"); } } /// <summary> /// 苹果手机,即装饰着模式中的具体组件类 /// </summary> public class Iphone : Phone { public override void Print() { Console.WriteLine("开始执行具体对象-苹果手机"); } } public class Redmi : Phone { public override void Print() { Console.WriteLine("开始执行具体对象-红米手机"); } } /// <summary> /// 手机贴膜 /// </summary> public class Sticker : Decorator { public Sticker(Phone phone) : base(phone) { } public override void Print() { // base.Print(); Console.WriteLine("开始贴膜"); AddSticker(); } /// <summary> /// 新的行为方法 /// </summary> public void AddSticker() { Console.WriteLine("现在小米手机有贴膜了"); } } /// <summary> /// 手机挂件 /// </summary> public class Accessories : Decorator { public Accessories(Phone phone) : base(phone) { } public override void Print() { // base.Print(); Console.WriteLine("开始挂挂件"); AddSticker(); } /// <summary> /// 新的行为方法 /// </summary> public void AddSticker() { Console.WriteLine("现在小米手机有挂件了"); } }
标签:Console,C#,void,模式,public,Phone,Print,手机,装饰 From: https://www.cnblogs.com/liujian1368928/p/16641065.html