At work we are reading “Head First Design Patterns” and discussing the “Observer Pattern” and some people wanted to see a code example.
The first part is the the class that manages the observer classes
In this example I created a generic class that has two basic parts a collection of subscribers or observers and a method that loops though and updates the state of the subscribers. I used a Dictionary<string,ISubscriber<T>> to make it easy to manage my subscribers based on a key, and because ISubscriber<T> is also a generic its a very flexible and strongly typed way to work with the subscribers.
Next let’s take a look at ISubscriber<T> interface
it’s that simple, I use generics to determine the state and the input type for the update method, here is an example implementation
TweetLocation is observing Location information and calls a Twitter class to Tweet the new location when updated, for something a little more complex
SaveLocation is basically the same as TweetLocation except it has it’s own EventManager to handle errors from failed attempts at saving the location.
Finally here is an example of actually using it
This is a simple console app that demonstrates adding subscribers, updating state, and removing a subscriber.
A real world example of using “Observer Pattern” is a service bus like NServiceBus or MassTransit, where an event driven application needs to send messages to one or more subscribers.
As always here is a link to the project source.