提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
提示:以下是本篇文章正文内容,下面案例可供参考
一、泛型单例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 泛型单例
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingleTon<T>where T:class,new ()
{
private static T t=default(T);
public static T instance
{
get
{
if (t==null)
{
t = new T();
}
return t;
}
}
}
二、泛型消息中心
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 消息号
/// </summary>
public enum Message
{
}
/// <summary>
/// 泛型消息中心 作用:解耦
/// </summary>
public class MessageMar<T> : SingleTon<MessageMar<T>>
{
/// <summary>
/// 存放消息的字典 消息号 回调方法
/// </summary>
public Dictionary<Message, Action<T>> dic = new Dictionary<Message, Action<T>>();
/// <summary>
/// 添加侦听
/// </summary>
/// <param name="message">消息号</param>
/// <param name="action">回调方法</param>
public void OnAddiener(Message message,Action<T>action)
{
if (dic.ContainsKey(message))
{
dic[message] += action;
}
else
{
dic.Add(message, action);
}
}
/// <summary>
/// 删除侦听
/// </summary>
/// <param name="message">消息号</param>
/// <param name="action">回调方法</param>
public void OnReMove(Message message, Action<T> action)
{
if (dic.ContainsKey(message))
{
dic.Remove(message);
}
}
/// <summary>
/// 进行广播
/// </summary>
/// <param name="message">消息号</param>
/// <param name="t"></param>
public void OnBroad(Message message,T t)
{
if (dic.ContainsKey(message))
{
dic[message](t);
}
}
}
三、用法
继承单例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cube:SingleTon<Cube>
{
public void OnCreat()
{
Debug.Log("我被单例调用了");
}
}
直接调用就好
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UserMy : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Cube.instance.OnCreat();
}
}
消息中心的用法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Exam : MonoBehaviour
{
int COUNT = 0;
// Update is called once per frame
void Update()
{
COUNT++;//广播一次
if (COUNT<2)
{
MessageMar<int>.instance.OnBroad(Message.one, 1);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UserMy : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Cube.instance.OnCreat();
MessageMar<int>.instance.OnAddiener(Message.one, OnCreats);
}
void OnCreats(int n)
{
Debug.Log(n + "这是我发的消息");
}
}
总结
例如:上边就是泛型单例及消息中心很好用,单例模式,适用于调用单一游戏对象身上的各种方法及变量,主要是违反了开闭原则,所以少用单例为妙,避免形成单例癖。
消息中心好处多多,能有效帮助你进行解耦