Unity之C#——委托与事件,观察者模式,猫和老鼠事例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lijianfex/article/details/78282351

委托与事件,观察者模式,猫和老鼠事例

    在Unity游戏开发中,我们经常需要在一个类中,调用另一个类中的方法,比如,当玩家进入到某个地方,敌人就开始攻击玩家。这时就需要利用委托与事件,设计观察者模式。

此处我们利用猫和老鼠来简单描述:

代码如下:

Cat.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _002_委托与事件_猫与老鼠
{/// <summary>
/// 猫类
/// </summary>
    class Cat
    {
        public string Name { get; private set; }
        public string Color { get; private set; }

        public delegate void CatComeEventHandler();
        public event CatComeEventHandler CatComeEvent;//声明“猫来了”的事件

        public Cat(string name,string color)
        {
            this.Name = name;
            this.Color = color;

        }

        public void CatCome()
        {
            Console.WriteLine(Color+"的猫,名字叫:"+Name+",跑过来了。。。");
            CatComeEvent();//触发“猫来了”的事件
        }
    }
}


Mouse.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _002_委托与事件_猫与老鼠
{
    /// <summary>
    /// 老鼠类
    /// </summary>
    class Mouse
    {
        public string Name { get; private set; }
        public string Color { get; private set; }

        public Mouse(string name,string color,Cat cat)
        {
            this.Name = name;
            this.Color = color;
            cat.CatComeEvent += this.MouseRun;//订阅“猫来了”的事件,并做出反应,老鼠逃跑 MouseRun
        }

        public void MouseRun()
        {
            Console.WriteLine(Color + "的" +Name+"老鼠,逃跑了");
        }

    }
}


Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _002_委托与事件_猫与老鼠
{
    /// <summary>
    /// Program类
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Cat Tom = new Cat("汤姆", "蓝色");
            Mouse Jerry = new Mouse("杰瑞", "灰色",Tom);
            Mouse Jack = new Mouse("杰克", "黑色",Tom);
            //Tom.CatComeEvent += new Cat.CatComeEventHandler(Jerry.MouseRun);
            //Tom.CatComeEvent+= new Cat.CatComeEventHandler(Jack.MouseRun);
            //Tom.CatComeEvent+= Jerry.MouseRun;
            //Tom.CatComeEvent += Jack.MouseRun;

            Tom.CatCome();
            Console.ReadKey();
        }
    }
}

点击运行效果如下:


欢迎交流,互相进步!GO GO!继续成长。

猜你喜欢

转载自blog.csdn.net/lijianfex/article/details/78282351