Listener design pattern (also known as Subscriber/Observer) is a 'well-proven' technique for asynchronous message passing. It is used when the client needs to be notified when 'something interesting' happens to another object (of class X
) in a passive manner (i.e. the client is not checking every so often (pulling) in the state has changed).
The Recipe
There are 4 simple steps in order to implement the listener design pattern:
- Create a listener (to observer) interface (
IXListener
) which contains appropriate notification method (e.g.Notify()
,setText
) - Add a list/array that holds references to attached listeners to class
X
- Add Methods to
X
so that clients can attach/detach listeners (objects that confirm to theIXListener
interface) - When the interesting event happens in
X
, notify all attached listeners
Code
There are various ways to implement the functionality. This is a .NET (a'la) Java design pattern. In .NET you can also use Events.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
interface IXListener { void Notify(); } class X { List<IXListener> Clients = new List<IXListener>(); public void Attach(IXListener client) { this.Clients.Add(client); } public void Detach(IXListener client) { this.Clients.Remove(client); } public void InterestingEvent() { Clients.ForEach(x => x.Notify()); } } class Client1 : IXListener { public void Notify() { // TO DO } } class Client2 : IXListener { public void Notify() { // TO DO } } |