Peter works on the web!

Archive for the ‘A Design Pattern A Day’ Category

A Design Pattern A Day: The Singleton Pattern

with one comment

The Singleton pattern, probably the most hated pattern on the internet. But for the sake of being complete I feel obligated in implementing it once. <sarcasm>And never use it again</sarcasm>. Although this pattern has its use cases in some scenario’s. Caching could be one of them. Mind the usage of ‘could’ in the previous sentence. It could be a use case but as always: it depends.

As usual, tests are written using MSpec, code can be found on the public Github repository and we’ll immediately get started with the definition of the pattern from the Gang of Four book:

Ensure a class only has one instance, and provide a global point of access to it.

I think this is a pretty well known pattern, a full explanation can be found on its Wikipedia page. For ASP.Net programmers that really don’t know what I’m talking about. You know the System.Web.HttpContext.Current property? Unfortunately, that’s a Singleton.

250px-Singleton_UML_class_diagram

Let’s get our hands dirty. We’re going to implement our girlfriend as a singleton, because we are all good guys there is only one true girlfriend in our lives. So that will be our singleton. Let’s start with the implementation of our singleton Girlfriend class:

   1:      public class Girlfriend
   2:      {
   3:          private static readonly Girlfriend _instance = new Girlfriend();
   4:   
   5:          private Girlfriend()
   6:          {
   7:              
   8:          }
   9:   
  10:          public static Girlfriend Instance
  11:          {
  12:              get
  13:              {
  14:                  return _instance;
  15:              }
  16:          }
  17:      }

So this class is pretty straightforward. Our class has a readonly static class member that is instantiated when declared. And there is a property which returns the instantiated member. The constructor is private, so we can only create a new instance of the class within the class itself. This way we ensure that no instance of the Girlfriend class is created outside our class.

Our implementation does not lazy instantiate our singleton. There are other implementations which do lazy instantiation but then you have to take multithreading into account. If you’re interested in that implementation, this page gives a nice explanation about the different implementations of the Singleton pattern in C#.

The first test we write is to check if we always get the same instance from our Instance property. We check it by using the GetHashCode function, like this:

   1:      [Subject("Getting the girlfriend")]
   2:      public class When_getting_the_girlfriend
   3:      {
   4:          Because of = () =>
   5:              _hashCode = Girlfriend.Instance.GetHashCode();
   6:   
   7:          It should_always_return_the_same_girlfriend = () =>
   8:          {
   9:              var hashCode = Girlfriend.Instance.GetHashCode();
  10:              _hashCode.ShouldEqual(hashCode);
  11:          };
  12:   
  13:          private static int _hashCode;
  14:      }

Not that difficult, we call the Instance method 2 times and compare the hash codes of both instances. In fact, this confirms that our singleton works. But to be complete, let’s implement another scenario.

The next scenario, a common problem for everyone. Our house is dirty, we haven’t been cleaning for weeks and now it needs cleaning. Because our girlfriend is the best in the world she always volunteers to clean the house. Forgive me the sexism. So we have the following test case:

   1:      [Subject("Getting the person that cleans the dirty house")]
   2:      public class When_getting_the_person_that_cleans_the_dirty_house
   3:      {
   4:          Establish context = () =>
   5:              _dirtyHouse = new DirtyHouse();
   6:   
   7:          Because of = () =>
   8:              {
   9:                  _girlFriend = Girlfriend.Instance;
  10:                  _personThatCleans = _dirtyHouse.CleaningPerson;
  11:              };
  12:   
  13:          It should_return_the_same_person_as_our_girlfriend = () =>
  14:              _girlFriend.GetHashCode().ShouldEqual(_personThatCleans.GetHashCode());
  15:              
  16:          private static DirtyHouse _dirtyHouse;
  17:          private static Girlfriend _girlFriend;
  18:          private static Girlfriend _personThatCleans;
  19:      }


There is the DirtyHouse class which exposes the person that is cleaning it via the CleaningPerson property. A separate variable is instantiated with the Girlfriend instance so we can compare the hash codes of the cleaning person and the girlfriend instance to ensure that both are the same instance. This test is actually obsolete because we are actually testing the Girlfriend class again instead of the DirtyHouse. But that’s outside the scope of this blog post.

This is the implementation of the DirtyHouse class:

   1:      public class DirtyHouse
   2:      {
   3:          public Girlfriend CleaningPerson
   4:          {
   5:              get
   6:              {
   7:                  return Girlfriend.Instance;
   8:              }
   9:          }
  10:      }


No rocket science there. So this concludes the implementation of the Singleton pattern. As mentioned there are different ways to implement the pattern. A definite improvement would be to create an interface for our Girlfriend class so we can mock or stub it when testing other classes that use the Singleton. For example the test for the DirtyHouse class should actually mock the Girlfriend class via its interface so we can only test the logic in the DirtyHouse class and not if the Girlfriend is a singleton. But again that is outside the scope of this blog post.

Want to read more about the Singleton pattern? Check out these links:

Written by Peter

September 15th, 2012 at 8:36 pm

A Design Pattern A Day: The Decorator Pattern

with 4 comments

Last week I started reading the Gang Of Four book for about the fifth time. Unfortunately I’m really bad at reading reference-like books. I always get bored after reading a few design patterns and put the book on my shelf to collect dust again. This time I’ve decided to do something different, because everybody knows:

If you keep doing what you’re doing, you’ll keep getting what you’re getting

So I decided that each design pattern that I read somewhere, be it on Twitter, on a blog
post or somewhere else I’m going to look up in the book of the Gang of Four, implement it and blog my implementation. Although the title of the series is ‘A Design Pattern A Day’, don’t take it literally. I will try to implement a design pattern as often as possible, but it won’t be daily. I just liked the name.

Because C# is what I’m still most fluent at, everything will be implemented in C# using the .Net framework 4.0. All implementations can be found on a public Github repository and we’re are all responsible programmers so all code is covered with unit tests written in MSpec. To get started with MSpec, read this excellent post by my ex-colleague Jan on Elegant Code.

The first design pattern I came across was the Decorator pattern. Let’s start with the definition of the pattern, what can it be used for? From the Gang Of Four book:

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

I’m not going to type out the whole explanation what the Decorator pattern consists of. You can read all about it on its Wikipedia page. If you’re that kind of guy, here is an UML schema for you which should explain it. Or mess things up even further if you’re that other kind of guy. Don’t worry, it will all click together if you see the implementation.

We’re going to use the Decorator pattern to measure and adapt the speed of a running dog. So we’re starting out with our base component, the Animal class which has a Run method. The Run method returns the speed in miles per hour the animal is running at. We can reuse this component class in the future to measure the speed of other animals.

   1:      public abstract class Animal
   2:      {
   3:          public abstract int Run();
   4:      }


We create our Dog class which inherits from Animal, a Dog is an Animal after all, and implement the Run method. After googling for 2 seconds I found out that a dog runs 25 miles per hour.

   1:      public class Dog : Animal
   2:      {
   3:          public override int Run()
   4:          {
   5:              return 25;
   6:          }
   7:      }


But alas, our dog doesn’t have a lot of luck in his life. He is hit by a car and becomes handicapped. Because of his handicap he can only run a third as fast as he could when he still had all his legs. We could subclass Dog an create a HandicappedDog but what if the next animal we get is a Pony and he gets hit by a car? Then we have to create a HandicappedPony which will have the same logic as the HandicappedDog class. And for the smart-asses: yes, when a pony loses a leg or a dog loses a leg they both lose a third of their original speed. I’m sorry but that’s just how things work in the real world.

Although the duplication is minimum, we still want to avoid it and instead of subclassing our Dog class we create a Decorator. We have a generic Decorator which allows us the quickly create a new Decorator.

   1:      public abstract class AnimalDecorator : Animal
   2:      {
   3:          protected Animal Animal;
   4:   
   5:          protected AnimalDecorator(Animal animal)
   6:          {
   7:              Animal = animal;
   8:          }
   9:   
  10:          public override int Run()
  11:          {
  12:              return Animal.Run(); 
  13:          }
  14:      }


We create a HandicappedDecorator which returns a third of the speed of the original Animal it is ‘decorating’. If we create a handicapped dog, you will notice that the speed of the handicapped dog is only 8 miles per hour.

   1:      public class HandicappedDecorator : AnimalDecorator
   2:      {
   3:          public HandicappedDecorator(Animal animal)
   4:              : base(animal)
   5:          {
   6:          }
   7:   
   8:          public override int Run()
   9:          {
  10:              return base.Run() / 3;
  11:          }
  12:      }
 

In the test of the HandicappedDecorator you can see how to use this Decorator:

   1:      [Subject("Measuring the speed of a running handicapped dog")]
   2:      public class When_measuring_the_speed_of_a_running_handicapped_dog
   3:      {
   4:          Establish context = () =>
   5:          {
   6:              _classUnderTest = new HandicappedDecorator(new Dog());
   7:          };
   8:   
   9:          Because of = () =>
  10:              _measuredSpeed = _classUnderTest.Run();
  11:   
  12:          It should_have_a_third_of_the_speed_of_a_normal_running_dog = () =>
  13:          {
  14:              var normalSpeed = new Dog().Run();
  15:              _measuredSpeed.ShouldEqual(normalSpeed/3);
  16:          };
  17:   
  18:          private static HandicappedDecorator _classUnderTest;
  19:          private static int _measuredSpeed;
  20:      }


But we miss the times that our dog ran 25 miles per hour and we buy him a pair of bionic legs to augment its speed. The bionic legs double the speed of the dog, so a normal dog will be running at 50 miles per hour.

   1:      public class BionicLegsDecorator : AnimalDecorator
   2:      {
   3:          public BionicLegsDecorator(Animal animal) : base(animal)
   4:          {
   5:          }
   6:   
   7:          public override int Run()
   8:          {
   9:              return base.Run() * 2;
  10:          }
  11:      }


The cool thing about this implementation is that we can ‘chain’ the decorators, so we can make a dog handicapped an give him a pair of bionic legs. So the handicapped dog runs at 16 miles per hour.

   1:      [Subject("Measuring the speed of a running handicapped dog with bionic legs")]
   2:      public class When_measuring_the_speed_of_a_running_handicapped_dog_with_bionic_legs
   3:      {
   4:          Establish context = () =>
   5:          {
   6:              _classUnderTest = new BionicLegsDecorator(new HandicappedDecorator(new Dog()));
   7:          };
   8:   
   9:          Because of = () =>
  10:              _measuredSpeed = _classUnderTest.Run();
  11:   
  12:          It should_have_a_speed_of_16_miles_per_hour = () =>
  13:              _measuredSpeed.ShouldEqual(16);
  14:   
  15:          private static BionicLegsDecorator _classUnderTest;
  16:          private static int _measuredSpeed;
  17:      }

So that was the Decorator pattern I hope you learned something, if you want to check out all code with tests, head over to the public Github repository. I found another implementation of the Decorator pattern in C# if you still want to know more.

And remember, a design pattern a day keeps the all-nighters away … Or something like that. As always, feedback, remarks? All welcome in the comments.

Written by Peter

June 16th, 2012 at 8:00 am