Design Patterns Series: The Decorator Pattern (with a real-world soccer example!)

Good News: You just landed a gig at as a developer for the Soccer department of ESPN! Bad News: Deadlines are tight and documented requirements are scarce.

In fact, the entire project is behind, but shortcuts and bad code are not tolerated and they need you to implement a robust system, due yesterday.

The Project: Implement a system that displays statistics for a given team.

The Challenge: In the requirements that are present, it specifies that you are to provide the basic win-loss-draw stats for each team, but you heard that more statistics will need to be developed. You don’t know when they will come and you don’t know which stats they will be. What you do know is that the generic functionality will have functionality to display the statistics in a tabular fashion.

They run a tight shop here, so a good OOP design is expected. Perhaps, one that adheres to the Open-Closed Principle, which in the Head First: Design Patterns text states that

Classes should be open for extension, but closed for modification.

This means that when they come to you with additional statistics, instead of creating additional lines in the existing class, creating the need to recode, recompile, and retest, you close the existing class, but code the structure in such a way that you can add extension classes using the principles you have learned so far.

This is where the Decorator Pattern comes in.

The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

With this pattern, you start out with an abstract class that will house the common functionality skeleton. Let’s call it the Component. In our case, there is the Display() method, and the team name. Our initial requirements state that we are going to display the W-L-D records for a team. At this point, we know we are definitely extending this abstract class, a.k.a. component, as a ConcreteComponent.

public abstract class TeamData
//Component
{
    public abstract string Display();
    public string TeamName;
    private string _teamName;
}

public class Matches : TeamData
//ConcreteComponent
{
    public int Wins {get; set;}
    public int Losses {get;set;}
    public int Draws {get;set;}

    public Matches(string teamName,int wins,int losses,int draws)
    {
        TeamName = teamName;
        Wins = wins;
        Losses = losses;
        Draws = draws;
    }

    public override string Display()
    {
        var sbStats = new StringBuilder();
        sbStats.Append("Team Name: " + TeamName);
        sbStats.Append("Record (W|L|D): ");
        sbStats.Append(Wins + "|");
        sbStats.Append(Losses + "|");
        sbStats.Append(Draws);

        return sbStats.ToString();

    }
}

We know more requirements are coming, so how do we plan for the future? We create another abstract class, a.k.a Decorator, inheriting the Component object, which is also an abstract class. Any extension classes, a.k.a. ConcreteDecorators, will have the benefit of following the functionality skeleton with the flexibility of creating custom functionality.

public abstract class TeamStatDecorator : TeamData
//Decorator
{
    protected TeamData teamData;
    public void AttachComponent(TeamData _teamData)
    {
        teamData = _teamData;
    }
    public override string Display()
    {
        if (teamData != null)
            teamData.Display();
    }
}

public class HomeAwayAdvantage : TeamStatDecorator
//ConcreteDecorator
{
    public int GoalsScoredHome { get; set; }
    public int GoalsScoredAway { get; set; }
    public int GoalsConcededHome { get; set; }
    public int GoalsConcededAway { get; set; }

    public HomeAwayAdvantage(int goalsScoredHome, int goalsScoredAway,
    int goalsConcededHome, int goalsConcededAway, string teamName)
    {
        TeamName = teamName; //inherited
        GoalsScoredHome = goalsScoredHome;
        GoalsScoredAway = goalsScoredAway;
        GoalsConcededHome = goalsConcededHome;
        GoalsConcededAway = goalsConcededAway;

    }
    public override string Display()
    {
        //first we call the class we inherit from - TeamStatDecorator
        base.Display();

        var sbStats = new StringBuilder();
        sbStats.Append("Team Name: " + TeamName);
        sbStats.Append("Goals Scored (Home|Away): ");
        sbStats.Append(GoalsScoredHome + "|" + GoalsScoredAway);
        sbStats.Append("Goals Conceded (Home|Away): ");
        sbStats.Append(GoalsConcededHome + "|" + GoalsConcededAway);

        return sbStats.ToString();
    }
}

If at any point we would need to add another statistic functionality, we inherit from the TeamStatDecorator. If you recall back, we mentioned that “has-a” relationships were preferred to inheritance and “is-a” relationships, but in our case, the classes are chained together at run-time. Take a look at the code below.

public class DecoratorExample
{

    static void Main()
    {
        // Create ConcreteComponent and decorator
        var matches = new Matches("Machester United", 9,2,1);
        var homeAwayAdvantage = new HomeAwayAdvantage("Machester United", 14, 3, 5, 4);
        //var otherDisplayType1 = new OtherDisplayType1();
        //var otherDisplayType2 = new OtherDisplayType2();

        // Link them
        homeAwayAdvantage.AttachComponent(matches);
        //otherDisplayType1.AttachComponent(homeAwayAdvantage);
        //otherDisplayType2.AttachComponent(otherDisplayType1);

        //call the last overridden method in the chain
        Console.WriteLine(homeAwayAdvantage.Display());
        //Console.WriteLine(otherDisplayType2.Display());

    }
}

Output:
Team Name: Manchester United
Record (W|L|D): 9 | 2 | 1

Team Name: Manchester United
Goals Scored (Home | Away): 14 | 3
Goals Conceded (Home | Away): 5 | 4

As you can see, we can keep adding decorators (otherDisplayType1,otherDisplayType2) without touching our main TeamData abstract class. If we want custom functionality with the decorators, we simply put it into the decorator abstract class and stick to the open-closed principle.

Hope this made sense. Would love to hear your feedback!

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.