对设计模式的地位早已有所耳闻,但最近终于可以抽出时间来好好学习一下,自己最近也将会使用到,于是今天便来把我的收获拿来分享一下
观察者模式的本质就是我发送你接收的这种模型,写个简易的例子
先定义一个接口名为: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 () { } }
就这么多吧,第一次写,真的不太会讲述,我会慢慢努力,总之多学习几遍,这个设计模式还是十分好用而且易于理解的