Design Patterns (e) decorative pattern

Decorative pattern

Add more features to an existing dynamic way modules, more flexible than the subclass. Able to play a decorative role logic classes removed from the main logic, simplifying the original class. eg tea can add pudding, pearl ...
Note that decorative objects directly require independent, concerned about their respective functions, otherwise the order will affect added.



    class MilkTea
    {
        private string name;

        public MilkTea()
        {
        }

        public MilkTea(string name)
        {
            this.name = name;
        }
        public virtual void Show()
        {
            Debug.LogFormat("{0}添加了", name);
        }
    }
    class Decorator : MilkTea
    {
        protected MilkTea person;
        public void Decorate(MilkTea de)
        {
            person = de;
        }

        public override void Show()
        {
            if (person != null)
            {
                person.Show();
            }
        }
    }
    class Test1 : Decorator
    {
        public override void Show()
        {
            base.Show();
            Debug.LogFormat("珍珠");
        }
    }
    class Test2 : Decorator
    {
        public override void Show()
        {
            base.Show();
            Debug.LogFormat("布丁");
        }
    }

    private void Awake()
    {
        MilkTea p = new MilkTea("奶茶");
        Test1 a = new Test1();
        Test2 b = new Test2();
        a.Decorate(p);
        b.Decorate(a);

        b.Show();
    }

Guess you like

Origin www.cnblogs.com/ZeroyiQ/p/12134643.html