Skip to content

Instantly share code, notes, and snippets.

@sujoyu
Last active August 4, 2016 10:59
Show Gist options
  • Save sujoyu/0c98b0e215d4d053ee7e87fbe9e78628 to your computer and use it in GitHub Desktop.
Save sujoyu/0c98b0e215d4d053ee7e87fbe9e78628 to your computer and use it in GitHub Desktop.
A simple weak event pattern by C# for Game.
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();
}
}
@sujoyu
Copy link
Author

sujoyu commented Aug 4, 2016

Usage

new EventListener ((e) => {
    // do something.
}).Listen(new GameEvent("click"));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment