Unity中的設計模式--觀察者模式
阿新 • • 發佈:2019-01-09
對設計模式的地位早已有所耳聞,但最近終於可以抽出時間來好好學習一下,自己最近也將會使用到,於是今天便來把我的收穫拿來分享一下
觀察者模式的本質就是我傳送你接收的這種模型,寫個簡易的例子
先定義一個介面名為:IObserver
該介面負責 新增被觀察者,通知被觀察者
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IObserver { List<ISubject> observer { get; set; } void Notify(); void AddSubject(ISubject subject); }
在新增一個被觀察者介面:ISubject
該介面負責定義被通知者接到通知後要做什麼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface ISubject {
void WhatCanYouDo();
}
接著定義Observer類和Subject類,並繼承實現上文兩個介面
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Observer : IObserver { public Observer() { _observer = new List<ISubject>(); } private List<ISubject> _observer; public List<ISubject> observer { get { return _observer; } set { _observer = value; } } /// <summary> /// 新增被觀察者 /// </summary> /// <param name="subject"></param> public void AddSubject(ISubject subject) { Debug.Log(subject); if(subject!=null&&!_observer.Contains(subject)) { _observer.Add(subject); } } public void Notify() { foreach(var xx in _observer) { xx.WhatCanYouDo(); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Subject :ISubject { private string _name; public Subject(string name) { _name = name; } /// <summary> /// 觀察者通知給被觀察者要做什麼事 /// </summary> public void WhatCanYouDo() { Debug.Log(_name+"出事了,快跑"); } }
接著最後一個類負責測試
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShiXian : MonoBehaviour {
void Start () {
Observer observer = new Observer();
Subject subject = new Subject("我是張家輝");
Subject subject_1 = new Subject("我是古天樂");
observer.AddSubject(subject);
observer.AddSubject(subject_1);
observer.Notify();
}
void Update () {
}
}
就這麼多吧,第一次寫,真的不太會講述,我會慢慢努力,總之多學習幾遍,這個設計模式還是十分好用而且易於理解的