Unity学习(C#)——观察者设计模式

定义猫类

 class Cat
    {
        private string name;
        private string color;
        public Cat(string name,string color)
    {
        this.name=name;
        this.color=color;

    }
            public void CatComing()
            {
                Console.WriteLine(color + "的猫" + name + "来了");
                if(catCome!=null)
                {
                    catCome();
                }

            }
            public event Action catCome;//声明一个事件,发布了一个消息
    }

定义鼠类

class Mouse
    {
        private string name;
        private string color;

        public Mouse(string name, string color,Cat cat)
        {
            this.name = name;
            this.color = color;
            cat.catCome += this.RunAway;
        }
        public void RunAway()
        {
            Console.WriteLine(color + "的老鼠" + name + "说:快跑啊,猫来了");
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat("加菲猫", "黄色");
            Mouse m1 = new Mouse("米老鼠", "黑色",cat);
            Mouse m2 = new Mouse("仓鼠", "灰色",cat);
            cat.CatComing();
           // cat.catCome();//声明为事件后,不能在外部触发,只能在能不调用
            Console.ReadKey();
        }
    }

你可能感兴趣的:(Unity学习(C#)——观察者设计模式)