Design Patterns - Decorative Patterns

public class Person
    {
        public Person()
        {
        }
        private string name;
        public Person(string _name)
        {
            this.name = _name;
        }        
        public virtual void show()
        {
            Console.WriteLine(string.Format("{0}开始show",name));
        }
    }
public class Fushi:Person
    {
        protected Person person;

        public void daban(Person _person)
        {
            this.person = _person;
        }
        public override void show()
        {
            if (person != null)
            {
                person.show();
            }
        }
    }
    public class xizhuang : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了西装");
            base.show();
        }
    }
    public class xiku : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了西裤");
            base.show();
        }
    }
    public class pixie : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了皮鞋");
            base.show();
        }
    }
    public class duanxiu : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了短袖");
            base.show();
        }
    }
    public class niuzaiku : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了牛仔裤");
            base.show();
        }
    }
    public class fanbuxie : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了帆布鞋");
            base.show();
        }
    }
前端
Person p = new Person("张三");
Fushi f1 = new xizhuang();
Fushi f2 = new xiku();
Fushi f3 = new pixie();
f1.daban(p);
f2.daban(f1);
f3.daban(f2);            
f3.show();

Design Patterns - Decorative Patterns
Summary: Decorative patterns are a way to dynamically add more functionality to existing functionality.
A bad design approach is to add new code to a class when the system needs new functionality. These newly added codes usually decorate the main behavior of the original class, while increasing the complexity of the class; and violate the open-closed principle.
The decoration pattern puts each function that needs to be decorated into a class separately, and let the class wrap the object that needs to be decorated.
Advantages: The class to be decorated can be simplified, the core responsibilities and decoration functions can be separated, and repeated logic can be removed

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324902904&siteId=291194637