设计模式-装饰模式

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();

设计模式-装饰模式
总结:装饰模式是为已有功能动态添加更多功能的一种方式。
错误的设计方法是当系统需要新功能时,向类中添加新的代码。这些新加的代码通常装饰了原有类的主要行为,同时增加了类的复杂度;并且违背开闭原则。
装饰模式把每个需要装饰的功能单独放到一个类中,并让类包装他需要装饰的对象。
优点:可以简化要装饰的类,把核心职责和装饰功能分离,去除重复逻辑

猜你喜欢

转载自blog.51cto.com/5591787/2108208