Unity3d-c#-观察者设计模式-猫抓老鼠

在这个例子中运用了委托事件机制
讲述了事件和委托的区别
最大的区别是:
事件是特殊的受限的委托,事件只能在类内部调用,不能在类的外部调用起到保护作用,可以在类的外部通过+=添加事件

1、首先是Cat的类代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class Cat {
private string name;
private string color;

public event Action catCome;//事件不能在类的外部触发,只能在类的内部触发。 委托都可以触发。
public Cat(string name,string color)
{
this.name=name;
this.color=color;
}

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

2、其次是Mouse的类代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Mouse {
private string name;
private string color;
public Mouse(string name,string color,Cat cat)
{
this.name=name;
this.color=color;
cat.catCome+=RunAway;
}

public void RunAway()
{
Debug.Log(color +"的老鼠"+name+"说猫来了");
}
}

3、最后是Main方法代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour {

// Use this for initialization
void Start () {
    Cat cat=new Cat("加菲猫","黄色");
    Mouse mouse1=new Mouse("米奇","黑色",cat);
    Mouse mouse2=new Mouse("airu","白色",cat);
    cat.CatComing();
    
}

// Update is called once per frame
void Update () {
    
}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,107评论 19 139
  • alert(a); function name(parameters) { alert(parameters); ...
    name阿喆azhe阅读 1,143评论 0 3
  • 1月21日日精进:敬畏—进入—体验—交给—持续 1,缺啥补啥,怕啥练啥; 2,一切为我所用,所用为团队家; 3,我...
  • 你不曾懂我 是你不曾试着懂我 不怨谁 你有你宝贝的人 我有我宝贝的人 你我乃是匆匆过客 谁去怨谁 何以...
    简苗阅读 250评论 2 1
  • 1 有这样一位大人物,他会在火车上口述一封信,让秘书帮自己写下来,会在汽车上为大型会议做准备,或是边吃午饭边开小会...
    大圣72阅读 1,510评论 21 31