单例模式
public class Manager
{
public static Manager Instance { private set; get; }
}
public class Manager
{
private static Manager _instance;
public static Manager Instance => _instance ?? (_instance = new Manager());
}
观察者模式
using System.Collections.Generic;
using System;
public static class EventManager
{
public static Dictionary<string, Action> EventPool = new Dictionary<string, Action>();
public void AddListener(string eventName, Action listener)
{
if (!EventPool.TryGetValue(eventName, out Action action))
{
action += listener;
EventPool.Add(eventName, action);
return;
}
EventPool[eventName] += listener;
}
public void RemoveListener(string eventName, Action listener)
{
if (EventPool.TryGetValue(eventName, out Action action))
{
if (EventPool[eventName] != null)
EventPool[eventName] -= listener;
}
else throw new Exception($"Event {eventName} is not in EventPool");
}
public void Broadcast(string eventName)
{
if (EventPool.TryGetValue(eventName, out Action action))
{
action?.Invoke();
}
}
public void Clear(string eventName)
{
if (EventPool.TryGetValue(eventName, out Action action))
{
EventPool[eventName] = null;
}
}
}