代码改变世界

老鼠,猫,主人的问题(委托学习系列一)

2012-02-16 12:15  秋日愚夫  阅读(306)  评论(0编辑  收藏  举报
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateDEMO
{
    //面试试题 老鼠,猫,主人的问题
    //由老鼠的活动引起老猫的醒,然后老猫在捉老鼠的时候,把主人吵醒
    //要保持类与类的低耦合,于是用委托实现。

    public delegate string WakeUp(); //定义委托

    //老鼠
    public class Mouse 
    {
        public string MouseAction()
        {
            return "我是JARRY,我是老鼠";
        }
    }

    //猫
    public class Cat
    {
        private WakeUp catWakeUp;
        public WakeUp CatWakeUp 
        {
            set { this.catWakeUp = value; }
            get { return this.catWakeUp; }
        }

        //Tom不会自己醒来,而是被某个对象的Action引起的,在本例中由老鼠Action引起的
        public string catAction()
        {
            return catWakeUp() + "\r\n我TOM猫醒了,我要捉老鼠";
        }
    }

    //主人
    public class Person
    {
        private WakeUp personWakeUp;
        public WakeUp PersonWakeUp
        {
            get { return this.personWakeUp; }
            set { this.personWakeUp = value; }
        }

        public string PersonAction()
        {
            return personWakeUp() + "\r\n Tom猫,把我弄醒了";
        }
    }
    
    
    class Program
    {
        static void Main(string[] args)
        {
            Mouse jarry = new Mouse();

            Cat tom = new Cat();
            //由Jarry的行动引发了Tom的醒来
            tom.CatWakeUp = new WakeUp(jarry.MouseAction);            

            Person hanliang = new Person();
            hanliang.PersonWakeUp = new WakeUp(tom.catAction);

            Console.Write( hanliang.PersonAction());
            Console.Read();
        }
    }
}