Unity3d-c#-觀察者設(shè)計模式-貓抓老鼠

在這個例子中運(yùn)用了委托事件機(jī)制
講述了事件和委托的區(qū)別
最大的區(qū)別是:
事件是特殊的受限的委托,事件只能在類內(nèi)部調(diào)用,不能在類的外部調(diào)用起到保護(hù)作用,可以在類的外部通過+=添加事件

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;//事件不能在類的外部觸發(fā),只能在類的內(nèi)部觸發(fā)。 委托都可以觸發(fā)。
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 () {
    
}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,551評論 19 139
  • alert(a); function name(parameters) { alert(parameters); ...
    name阿喆azhe閱讀 1,343評論 0 3
  • 1月21日日精進(jìn):敬畏—進(jìn)入—體驗—交給—持續(xù) 1,缺啥補(bǔ)啥,怕啥練啥; 2,一切為我所用,所用為團(tuán)隊家; 3,我...
  • 你不曾懂我 是你不曾試著懂我 不怨誰 你有你寶貝的人 我有我寶貝的人 你我乃是匆匆過客 誰去怨誰 何以...
    簡苗閱讀 275評論 2 1
  • 1 有這樣一位大人物,他會在火車上口述一封信,讓秘書幫自己寫下來,會在汽車上為大型會議做準(zhǔn)備,或是邊吃午飯邊開小會...
    大圣72閱讀 1,532評論 21 31

友情鏈接更多精彩內(nèi)容