Decorate模式 组合

装饰:修饰

Class Person     // 人有名字和形象。一个人逐渐发展,形象不断完善,如何避免多重继承?

Class PersonWrapper :Person  //包装类,对人进行修饰,专门用于扩展包装

//他可能硬汉,可能柔情,可能博学,可能多金...也可能既硬汉柔情,又博学多金...(完美的化身)

 class PersonYingHan:PersonWrapper   //硬汉包装类

 class PersonRouQing:PersonWrapper  //柔情包装类

 class PersonLearned:PersonWrapper  //博学包装类

 class PersonRich:PersonWrapper       //多金包装类

//实现源码

namespace DecorateMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person("小马");

            PersonYingHan yh = new PersonYingHan(p);
            yh.Show();

            PersonLearned bx = new PersonLearned(p);
            bx.Show();

            PersonRouQing rq = new PersonRouQing(p);
            rq.Show();

            PersonRich wlw = new PersonRich(p);
            wlw.Show();

            Console.WriteLine("*****牛比、不断升级的小马*****");

            Person p2 = new Person("小马");                     //以下体现Decorate模式精华! 扩展如此easy!     

            PersonYingHan PersonLevel1 = new PersonYingHan(p2);
            PersonRouQing PersonLevel2 = new PersonRouQing(PersonLevel1);
            PersonLearned PersonLevel3 = new PersonLearned(PersonLevel2);
            PersonRich PersonLevel4 = new PersonRich(PersonLevel3);

            PersonLevel4.Show();

            Console.ReadLine();
        }
    }
    class Person
    {
        public Person()
        { }

        private string name;
        public Person(string name)
        {
            this.name = name;
        }

        public virtual void Show()
        {
            Console.WriteLine("装扮的{0}:", name);
        }
    }
    class PersonWrapper:Person
    {
        protected Person component;
        public PersonWrapper(Person component)
        {
            this.component = component;
        }

        public override void Show()
        {
            if (component != null)
            {
                component.Show();
            }
        }
    }
    class PersonYingHan:PersonWrapper
    {
        public PersonYingHan(Person p)
            :base(p)
        {

        }
        public override void Show()
        {
            Console.WriteLine("硬汉形象!");
            base.Show();
        }
    }
    class PersonRouQing:PersonWrapper
    {
        public PersonRouQing(Person p)
            :base(p)
        {

        }
        public override void Show()
        {
            Console.WriteLine("温柔形象!");
            base.Show();
        }
    }
    class PersonLearned:PersonWrapper
    {
        public PersonLearned(Person p)
            :base(p)
        {

        }
        public override void Show()
        {
            Console.WriteLine("博学多才形象!");
            base.Show();
        }
    }
    class PersonRich:PersonWrapper
    {
        public PersonRich(Person p)
            :base(p)
        {

        }
        public override void Show()
        {
            Console.WriteLine("钻石王老五形象!");
            base.Show();
        }
    }
}

 

你可能感兴趣的:(ora)