Skip to content
David Cumps
Design Patterns - Observer/Event Pattern

Design Patterns - Observer/Event Pattern

Originally published on my old blog at cumps.be on June 27, 2008.

Yesterday I described the Observer Pattern and mentioned that the .NET CLR provides this functionality through events and delegates.

Let’s have a look at how to implement this.

First of all, we can get rid of our ISubject and IObserver interfaces and replace them with a push notification mechanism.

Push, because we’ll pass the required information along to the observers when notifying them, as opposed to pull, where the observers had to extract it themselves from the subject.

Since we’ll be pushing out the information, we need a custom class defining which information is interesting. We’ll create this by inheriting from the EventArgs class. That makes it very easy to set up an event in the next step.

Custom EventArgs Class

As you can see, this is a very small class, with a descriptive name, containing the new location of our unit.

You can’t see it on this diagram, but the NewLocation property only has a public getter, and a private setter, since our observers will only have to extract data from this class.

So, we have our small information-holding class. Now it’s time to change our GameUnit class to get rid of all the logic of maintaining a list of observers and subscription logic.

We’ll replace the ISubject logic with an event of the type EventHandler<PositionChangedEventArgs>. By doing this, we expose an event (PositionChanged) to which our observers can subscribe whenever they want, as well as unsubscribe when needed.

Observer/Event Pattern

Note that this event is strongly typed, containing a strongly typed information set, making it easy for our observers to get the information they need.

Using this method, we can have a set of EventArgs classes as small data holders, after which subjects can expose events using those custom EventArgs to the outside world, making sending out notifications very easy.

Observers on their side can easily subscribe to any of the events exposed by using a single line of code, and perform their logic (the _PositionChanged methods) whenever they get a notification.

Have a look at the uploaded solution to see the exact syntax of this method. We’re using delegates with generics, the += operator, and raising and handling events.

Some additional information on the Observer/Event pattern:

You May Also Like