Last active
August 4, 2016 10:59
-
-
Save sujoyu/0c98b0e215d4d053ee7e87fbe9e78628 to your computer and use it in GitHub Desktop.
A simple weak event pattern by C# for Game.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
// Static singleton class. | |
// There is no necessary to access this class directly. | |
public class EventManager { | |
private static Dictionary<GameEvent, List<WeakReference>> listeners = | |
new Dictionary<GameEvent, List<WeakReference>>(); | |
public static void AddListener(EventListener listener, GameEvent e) { | |
if (!listeners.ContainsKey(e)) { | |
listeners [e] = new List<WeakReference> (); | |
} | |
listeners [e].Add (new WeakReference(listener)); | |
} | |
public static void RemoveListener(EventListener listener, GameEvent e) { | |
RemoveListener (new WeakReference (listener), e); | |
} | |
public static void RemoveListener(WeakReference reference, GameEvent e) { | |
listeners [e].Remove (reference); | |
} | |
public static void Trigger(GameEvent e) { | |
if (listeners.ContainsKey(e)) { | |
listeners [e].ToList().ForEach ((r) => { | |
if (r.IsAlive) { | |
((EventListener)r.Target).on(e); | |
} else { | |
RemoveListener(r, e); | |
} | |
}); | |
} | |
} | |
} | |
// Mainly using class. | |
public class EventListener { | |
public readonly Action<GameEvent> on; | |
private List<GameEvent> events; | |
public EventListener(Action<GameEvent> on) { | |
this.on = on; | |
events = new List<GameEvent> (); | |
} | |
// Attach this listener to the event. | |
public EventListener Listen(GameEvent e) { | |
events.Add (e); | |
EventManager.AddListener (this, e); | |
return this; | |
} | |
public void Dispose() { | |
events.ForEach((e) => EventManager.RemoveListener(this, e)); | |
} | |
} | |
// This class can be customized. | |
public class GameEvent { | |
public readonly string name; | |
public GameEvent(string name) { | |
this.name = name; | |
} | |
public override string ToString() { | |
return "GameEvent (" + name + ")"; | |
} | |
public override bool Equals (object obj) { | |
if (obj == null || obj.GetType() != GetType()) { | |
return false; | |
} | |
var e = (GameEvent)obj; | |
return e.name == name; | |
} | |
public override int GetHashCode() { | |
return name.GetHashCode(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage