Design Patterns Series: The Observer Pattern

During last night’s Superbowl game – did you pay attention to the score box at the top-left corner? Think about the code you would write to do the keep the score up to date.  Would you get it to poll every couple of seconds for updates?  Let’s also say that hypothetically the same system fed the updates to NFL.com.  Are you going to have multiple systems now checking for updates? Or, is there perhaps a better way to do this?


If you recall the my post about design patterns, this problem has also been solved for you.  The design pattern that solves it is called The Observer Pattern and it too is described beautifully in the book on which this series is based: Head First Design Patterns.

Here is the definition from the text:

“The Observer Pattern defines a one-to-many relationship between a set of objects.  When the state of one object changes, all of its dependents are notified.

Lightbulb, yes? Hopefully? How about building a “push” type of notification mechanism that will notify the scoreboard, website, and any other subscriber that cares to be informed of the score?

Before we get into the code details, it’s important to visualize it from an architecture design perspective.

Subject (abstract)
registerObserver()
removeObserver()
notifyObservers()

The Subject abstract class gets implemented by a real, a.k.a. concrete subject like the main score keeping system.  So now, this system can register many observers, like scoreboards, websites, phones, etc., as well as remove them, and mass notify them.  This ISubject has an IObserver interface that has a single method called update().  This interface gets implemented by an actual observer that has implements this method which may update the scoreboard, phone app, or a website RSS feed.  For this to happen though, it must instantiate the concrete observer and register with it, which says “Hey, I’d like to subscribe to your events.  Please push an update to me anytime there is one and I’ll do my own thing to update my interface – and don’t worry, because you don’t have to know the details.  You and I are loosely coupled that way.”

Another great example of loose coupling here.  If the score keeping system had to know the details of how to update a website, a phone app, a TV scoreboard, and a bunch of other devices, not only would you have a humungous amount of lines in your code, but you would also have to recompile and retest anytime you wanted to add a new device implementation.  With loose coupling, that’s hidden in the actual observer object so that all the Subject has to know is that that device is registered and to send it an update when one exists.

Now that we see the benefit, let’s take a look at how you would implement the C# code for this.
Quick disclaimer: The .NET Framework has given us events and delegates, and while there are many ways to skin a cat and do this several ways, I am just using C# to show you the underlying object-oriented code to get this to work.

We create an interface for Observer and an abstract class for Subject
IObserver.cs

using System;

public interface IObserver
{
     void Update(object subject);
}

Subject.cs

using System;
using System.Collections;

public abstract class Subject
{
    private ArrayList observers = new ArrayList();

    public void AddObserver(Observer observer)
    {
         observers.Add(observer);
    }

    public void RemoveObserver(Observer observer)
    {
        observers.Remove(observer);
    }

    public void Notify()
    {
          foreach(Observer observer in observers)
          {
               observer.Update(this);
          }
     }
}

ScoreKeeper.cs

public class ScoreKeeper : Subject
{
      public int TeamOneScore {get;set;}
      public int TeamTwoScore {get;set;}

    //could be called by the master score keeper
    public void ChangeScore(int scoreOne,int scoreTwo)
    {
         TeamOneScore = scoreOne;
         TeamTwoScore = scoreTwo;

          Notify();
     }
}

ScoreWebForm.cs

public class ScoreWebForm : IObserver
{
       public void Update(object subject)
       {
            //let's make sure the right subject
            //called this method.
            if(!(subject is ScoreKeeper)
               return;

            //update asp:label web controls
           labelScore1.Text = ((ScoreKeeper)subject).TeamOneScore;
           labelScore2.Text = ((ScoreKeeper)subject).TeamTwoScore;
     }
}

There you have it.  Another problem solved by design patterns.  Hopefully, if you have not heard about design patterns before, you are slowly beginning to see the value.  Make sure to catch the entire series on my blog and get yourself a copy of the above mentioned book if you haven’t already done so.

Design Patterns Series: The Strategy Pattern

To use the example from Head First: Design Patterns, suppose you have a class called Duck and two classes that inherit it: MallardDuck and RedheadDuck.

Duck
quack()
swim()
display()
fly()

What happens when you are asked to implement a RubberDuck class? A RubberDuck does not fly() or quack() so the design is a bit off.  This is actually a great example that illustrates that a “has a” relationship is better than an “is a” relationship.  Instead of inheriting from a Duck superclass, we will be inheriting some interfaces, that represent behaviors – FlyBehavior and QuackBehavior.

The Strategy Pattern, as the book describes it is, “defines a family of algorithms, encapsulates each one, and makes them interchangeable.  Strategy lets the algorithm vary independently from clients that use it.”   Here is what the Duck class looks like after we apply the Strategy pattern.
Client

Duck
FlyBehavior flybehavior
QuackBehavior quackBehavior
swim()
display()
setFlyBehavior()
setQuackBehavior()

encapsulates

FlyBehavior (interface)
fly()

inherited by

FlyWithWings
fly()

and

FlyNoWay (used by RubberDuck)
fly()

Similarly, you can have apply the same principle to QuackBehavior.

Here is what the code looks like in C#.

public abstract class Duck
{
  QuackBehavior quackBehavior;
  FlyBehavior flyBehavior;
}
public class MallardDuck : Duck
{
   public MallardDuck()
   {
        flyBehavior = new FlyWithWings();
        quackBehavior = new Quack();
   }
}
public class RubberDuck : Duck
{
     flyBehavior = new FlyNoWay();
     quackBehavior = new QuackNoWay();
}

The takeaway here is to use behaviors, or has-a relationships on entities that might change later on so that you don’t have to rewrite the parts of the code or class that do not change.