201802181505->深入浅出设计模式:c#装饰者模式

xiaoxiao2021-02-28  47

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _008装饰者模式 {     /*--------------------------------------------抽象模式--------------------------------------------*/     public abstract class Phone     {         public abstract void Print();     }     public class Iphone : Phone     {         public override void Print()         {             Console.WriteLine("苹果手机...");         }     }     /*--------------------------------------------抽象模式--------------------------------------------*/     /*--------------------------------------------装饰具体指导类--------------------------------------------*/     public class Derector : Phone     {         private Phone mPhone;         public Derector(Phone phone)         {             mPhone = phone;         }         public override void Print()         {             Console.WriteLine(string.Format("手机组件{0}", mPhone.GetHashCode()));         }     }     /*--------------------------------------------装饰具体指导类--------------------------------------------*/     /*--------------------------------------------具体装饰类--------------------------------------------*/     public class PhoneScreen : Derector     {         public PhoneScreen(Phone phone) : base(phone)         {         }         public override void Print()         {             base.Print();             Console.WriteLine("已经加入屏幕...");         }     }     public class PhoneBattery : Derector     {         public PhoneBattery(Phone phone) : base(phone)         {         }         public override void Print()         {             base.Print();             Console.WriteLine("已经加入电池...");         }     }     /*--------------------------------------------具体装饰类--------------------------------------------*/     internal class Program     {         private static void Main(string[] args)         {             Phone phone = new Iphone();             phone.Print();             PhoneScreen screen = new PhoneScreen(phone);             screen.Print();             PhoneBattery battery = new PhoneBattery(phone);             battery.Print();             /*              * 装饰者模式与继承有几分相似,但装饰者模式更具灵活性,如果下次利用继承实现某功能,可以先考虑装饰者模式              *              * 子类持有父类的对象,对其性能进行拓展,就是装饰勒              *              * 优点:更利于拓展,拓展更仔细              *              * 缺点:子类多容易失控,尤其子类功能相似的时候              *              */             Console.ReadKey();         }     } }
转载请注明原文地址: https://www.6miu.com/read-2622186.html

最新回复(0)