Prototipo de delegado de patrón de observador:
En el delegado, agregue o elimine oyentes a través del diccionario.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 观察者模式
/// </summary>
public class EventDispather : Singleton<EventDispather>
{
//委托原型
public delegate void OnActionHandler(params object[] parmas);
//委托字典
private Dictionary<int,List<OnActionHandler>> dic = new Dictionary<int, List<OnActionHandler>>();
/// <summary>
/// 添加监听
/// </summary>
/// <param name="id"></param>
/// <param name="handler"></param>
public void AddEventListenner(int id, OnActionHandler handler)
{
if (dic.ContainsKey(id))
{
dic[id].Add(handler);
}
else
{
List<OnActionHandler> ishandle = new List<OnActionHandler> ();
ishandle.Add(handler);
dic[id] = ishandle;
}
}
/// <summary>
/// 移除监听
/// </summary>
/// <param name="id"></param>
/// <param name="handler"></param>
public void RemoveEventListenner(int id, OnActionHandler handler)
{
if(dic.ContainsKey(id))
{
List<OnActionHandler > ishandle = dic[id];
ishandle.Remove(handler);
if(ishandle.Count == 0)
{
dic.Remove(id);
}
}
}
/// <summary>
/// 派发消息
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
public void DisPath(int id, params object[] parmas)
{
if(dic.ContainsKey(id) )
{
List<OnActionHandler> ishandler = dic[id];
if(ishandler.Count > 0 && ishandler != null)
{
for (int i = 0; i < ishandler.Count; i++)
{
if (ishandler[i] != null)
{
ishandler[i](parmas);
}
}
}
}
}
}
Mensaje enviado:
/// <summary>
/// 消息发送者
/// </summary>
public class EventSend : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp(KeyCode.A))
{
EventDispather.instance.DisPath(0, 9);
}
else if (Input.GetKeyUp(KeyCode.B))
{
EventDispather.instance.DisPath(1, 18);
}
}
}
Los observadores escuchan:
Observador A:
/// <summary>
/// 消息监听A,监听2个消息
/// </summary>
public class EventGetA : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
EventDispather.instance.AddEventListenner(0, Masege0);
EventDispather.instance.AddEventListenner(1, Masege1);
}
private void Masege1(object[] parmas)
{
Debug.Log((int)parmas[0] + "点下班");
}
private void Masege0(object[] parmas)
{
Debug.Log((int)parmas[0] + "点上班");
}
private void OnDestroy()
{
EventDispather.instance.RemoveEventListenner(0, Masege0);
EventDispather.instance.RemoveEventListenner(1, Masege1);
}
}
Observador B:
/// <summary>
/// 消息监听B,只监听其中一个消息
/// </summary>
public class EventGetB : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
EventDispather.instance.AddEventListenner(1, Masege1);
}
private void Masege1(object[] parmas)
{
Debug.Log((int)parmas[0] + "点下班");
}
private void OnDestroy()
{
EventDispather.instance.RemoveEventListenner(1, Masege1);
}
}
ventaja:
- El patrón de observador puede evitar la aceptación innecesaria de mensajes por parte de los delegados ordinarios.
-Reduce la relación de acoplamiento entre el objetivo y el observador, y existe una relación de acoplamiento abstracta entre los dos. Cumple con el principio de inversión de dependencia.
- Se establece un mecanismo de activación entre el objetivo y el observador.
defecto:
- La dependencia entre el objetivo y el observador no está completamente resuelta, pudiendo producirse referencias circulares.
- Cuando hay muchos objetos observadores, la publicación de notificaciones lleva mucho tiempo, lo que afecta la eficiencia del programa.