Listener Design Pattern

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:

  1. Create a listener (to observer) interface (IXListener) which contains appropriate notification method (e.g. Notify(), setText)
  2. Add a list/array that holds references to attached listeners to class X
  3. Add Methods to X so that clients can attach/detach listeners (objects that confirm to the IXListener interface)
  4. 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.

Leave Comment

Your email address will not be published.

Please type the characters of this captcha image in the input box

Please type the characters of this captcha image in the input box