Last active
December 29, 2015 02:19
-
-
Save akouryy/7599460 to your computer and use it in GitHub Desktop.
This is a sample of event implementation on C#. output: 1HeLLo, WorLd! : on B 1 Hello, World! : on E(1) 1H ello, World! : on E(2) -11 : on D 11 : on E(1) 11 : on E(1) 22 : on E(2) 22 : on E(2)
This file contains 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; | |
using System.Text; | |
namespace Project1 { | |
class Program { | |
static void Main(string[] args) { | |
EventManager em = new EventManager(); | |
A a = new A(em); | |
B b = new B(em); | |
C c = new C(em); | |
D d = new D(em); | |
E e1 = new E(em, 1); | |
E e2 = new E(em, 2); | |
a.foo("Hello, World!"); | |
c.foo(10); | |
} | |
} | |
interface Event {} | |
class AEvent : Event { | |
public string Value{get; set;} | |
public AEvent(string s) { | |
Value = s; | |
} | |
} | |
class CEvent : Event { | |
public int Value{get; set;} | |
public CEvent(int i) { | |
Value = i; | |
} | |
} | |
class EventManager { | |
private Dictionary<Type, List<Action<Event>>> listeners = new Dictionary<Type, List<Action<Event>>>(); | |
public void addListener<T>(Action<T> a) where T : Event { | |
if(!listeners.ContainsKey(typeof(T))) | |
listeners[typeof(T)] = new List<Action<Event>>(); | |
listeners[typeof(T)].Add(e => a((T)e)); | |
} | |
public void HappenEvent(Event e) { | |
List<Action<Event>> actions = listeners[e.GetType()]; | |
if(actions != null) | |
actions.ForEach(action => action(e)); | |
} | |
} | |
class A { | |
private EventManager em; | |
public A(EventManager em) { | |
this.em = em; | |
} | |
public void foo(string s) { | |
em.HappenEvent(new AEvent(1 + s)); | |
} | |
} | |
class B { | |
private EventManager em; | |
public B(EventManager em) { | |
this.em = em; | |
em.addListener<AEvent>(e => Console.WriteLine(e.Value.Replace("l", "L") + " : on B")); | |
} | |
} | |
class C { | |
private EventManager em; | |
public C(EventManager em) { | |
this.em = em; | |
} | |
public void foo(int i) { | |
em.HappenEvent(new CEvent(1 + i)); | |
} | |
} | |
class D { | |
private EventManager em; | |
public D(EventManager em) { | |
this.em = em; | |
em.addListener<CEvent>(e => Console.WriteLine((-e.Value) + " : on D")); | |
} | |
} | |
class E { | |
private EventManager em; | |
public E(EventManager em, int i) { | |
this.em = em; | |
em.addListener<CEvent>(e => Console.WriteLine(e.Value * i + " : on E(" + i + ")")); | |
em.addListener<AEvent>(e => Console.WriteLine(e.Value.Insert(i, " ") + " : on E(" + i + ")")); | |
em.addListener<CEvent>(e => Console.WriteLine(e.Value * i + " : on E(" + i + ")")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment