装饰者模式

装饰者模式:动态给一个类新增一些新的行为。

UML图:

示例代码:

    public abstract class Phone
    {
        public abstract void Print();
    }
    public class ApplePhone:Phone
    {
        public override void Print()
        {
            Console.WriteLine("我是苹果手机");
        }
    }
    public class Decoretor:Phone
    {
        private Phone phone { get; set; }

        public Decoretor(Phone phone)
        {
            this.phone = phone;
        }

        public override void Print()
        {
            this.phone.Print();
        }
    }
    public class Sticker:Decoretor
    {
        public Sticker(Phone phone) : base(phone)
        {
        }

        public override void Print()
        {
            base.Print();
            AddOperation();
        }

        public void AddOperation()
        {
            Console.WriteLine("贴膜");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Phone phone = new Sticker(new ApplePhone());
            phone.Print();
        }
    }
原文地址:https://www.cnblogs.com/chenyishi/p/9110042.html