Unity 设计模式之 观察者模式的实例介绍

 时间:2024-11-09 15:07:24

1、打开Unity,新建一个空工程,具体如下图

Unity 设计模式之 观察者模式的实例介绍

2、在工程中,新建几个脚本,然后双击打开,具体如下图

Unity 设计模式之 观察者模式的实例介绍

3、脚本的具体代码和代码内容如下图

Unity 设计模式之 观察者模式的实例介绍
Unity 设计模式之 观察者模式的实例介绍
Unity 设计模式之 观察者模式的实例介绍
Unity 设计模式之 观察者模式的实例介绍
Unity 设计模式之 观察者模式的实例介绍
Unity 设计模式之 观察者模式的实例介绍

4、ISubject 脚本具体内容如下:///<summary>///抽象主题///</summary>publicinterfaceISubject{voidNotify();}

5、Customer 脚本具体内容如下:us坡纠课柩ingSystem.Collections;usingSystem.Coll髫潋啜缅ections.Generic;usingUnityEngine;usingSystem.Runtime.InteropServices;usingSystem;///<summary>///声明委托///</summary>publicdelegatevoidCustomerEventHandler();///<summary>///具体主题///</summary>publicclassCustomer:ISubject{privatestringcustomerState;publicstringCustomerState{ get{ returncustomerState; } set{ customerState=value; } }//声明一个委托事件,类型为CustomerEventHandler publiceventCustomerEventHandlerUpdate;publicvoidNotify() { if(Update!=null){Console.WriteLine("通知事件");//使用事件来通知给订阅者 Update(); } }}

6、Accountant脚本具体内容如下:usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingSystem;///<summary>///财务,已经不需要实现抽象的观察者类,并且不用引用具体的主题///</summary>publicclassAccountant{privatestringaccountState;publicAccountant(){ }///<summary> ///开发票 ///</summary> publicvoidGiveInvoice(){Debug.Log("会计师,来开发发票"); accountState="已开发票"; }}

7、Cashier脚本具体内容如下:usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingSystem;///<summary>///出纳,已经不需要实现抽象的观察者类,并且不用引用具体的主题///</summary>publicclassCashier{privatestringcashierState;publicCashier(){} ///<summary> ///记账 ///</summary> publicvoidRecoded(){Debug.Log("出纳员,来登记入账"); cashierState="已入账"; }}

8、Dilliveryman脚本具体内容如下:usingSystem.Collections;usingSystem.Collections.G髫潋啜缅eneric;usingUnityEngine;usingSystem;///<summary>///配送员,已经不需要实现抽象的观察者类,并且不用引用具体的主题///</summary>publicclassDilliveryman{privatestringdilliverymanState;publicDilliveryman(){}///<summary> ///发货 ///</summary> publicvoidDilliver(){Debug.Log("配送员,来发货"); dilliverymanState="已发货"; }}

9、Test脚本具体内容如下:usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingSystem;publicclassTest:MonoBehaviour{Customersubject;//Usethisforinitialization voidStart(){//观察对象 subject=newCustomer();//观察者 Accountantaccountant=newAccountant(); Cashiercashier=newCashier(); Dilliverymandilliveryman=newDilliveryman();//注册事件 subject.Update+=accountant.GiveInvoice; subject.Update+=cashier.Recoded; subject.Update+=dilliveryman.Dilliver;} //Updateiscalledonceperframe voidUpdate(){//状态改变,通知观察者 if(Input.GetKeyDown(KeyCode.A)){ Debug.Log("客户已付款"); subject.CustomerState="客户已付款"; subject.Notify(); } }}

10、脚本编译正确,回到Unity界面,在场景中新建一个 GameObject,并把 Test 脚本赋给 GameObject,具体如下图

Unity 设计模式之 观察者模式的实例介绍

11、运行场景,然后 按下 A 键,控制台 Console 打印如下图

Unity 设计模式之 观察者模式的实例介绍

12、到此,《Unity 设计模式之 观察者模式的实例介绍》讲解结束,谢谢

  • 漫野奇谭森林化怎么获得
  • 风暴英雄2.0新英雄——菲尼克斯技能介绍
  • 神舟战神Z8-KL7S2顶配版开箱评测
  • 神都夜行录如何骑乘坐骑
  • 如何使用uaf影音的半数尺寸功能?
  • 热门搜索
    清明节手抄报大全漂亮 小学四年级手抄报 手抄报教师节 教师节手抄报大全图片 六一儿童节手抄报图片 诚信手抄报内容 成长的足迹手抄报 推广普通话手抄报内容 英语国庆手抄报 雾霾手抄报