装饰模式

 /// <summary>
    /// 装饰模式的基类
    /// </summary>
    public class Person
    {
        private string name;

        /// <summary>
        /// 子类使用无参构造函数,所以父类必须有这个构造函数
        /// 构造函数的调用顺序是从父类开始,然后调用子类
        /// </summary>
        public Person()
        {
        }

        public Person(string n)
        {
            name = n;
        }

        /// <summary>
        /// 多态方法,使得对象可以是用装饰,也可以不使用装饰
        /// 如加密数据要保存到数据库,则不需要使用加密
        /// </summary>
        public virtual void Oporation()
        {
            Console.Write("decorate " + name);
        }
    }

    /// <summary>
    /// 加入一层装饰的具体类
    /// 它和父类是一类对象,是对父类功能的扩展,所以使用继承
    /// </summary>
    public class DecoratePerson:Person
    {
        private Person person;

        /// <summary>
        /// 设置要装饰的对象
        /// </summary>
        /// <param name="p"></param>
        public void SetPerson(Person p)
        {
            person = p;
        }

        public override void Oporation()
        {
            //调用一个对象的方法前,首先要确定该对象不为空
            if (person != null)
            {
                person.Oporation();
                Console.Write("put on traveserse");
            }
        }
    }

    public class TestClass
    {
        public static void Run()
        {
            Person p = new Person("xiao");
            DecoratePerson dp = new DecoratePerson();
            dp.SetPerson(p);
            dp.Oporation();
        }
    }

 

装饰模式

posted @ 2013-08-23 14:23  viola  阅读(160)  评论(0编辑  收藏  举报