Category Archives: Creational Patterns

Singleton Pattern

Highlander

 

I did never really care about programming patterns. I had to come up with ideas when I needed them. And back in the Commodore 64 ages, when I wrote my first “Hello World” program in Basic, there was no book about patterns anyway.

When you only allow one object instance, that is called Singleton.

Have you ever come across Remoting? You send a request to a server. There is a choice between Singleton and SingleCall. It basically means that you:

  • Always use the same object or
  • create a new object for each request.

Let’s say you order 4 pints of beer using your tablet PC rather than calling the sexy, blond, and 18-year-old waitress. You obviously want 4 pints at once. Therefore the correct choice would be SingleCall; 4 distinct objects. The geeky waitress reacts. She responds via her high-tech cash register: “Who are you?”. She could ask that 10 times and unless you get upset, you would always give the same answer. Any good programmer realizes that this would only require one object instance – a Singleton.

There are several ways to do this. The conceptual idea is pretty easy. (Wikipedia has some more details.) In this post I am only giving you my favourite pattern, which should always work. You don’t need more unless you want to show off with some cheap stuff.

 

Example:

Remove the sealed keyword in case you need to make the class inheritable.
Notice the double-check if (_Instance == null) ...

The reason is:

  • The first check avoids entering the lock in 99.9999% of the calls. You save precious processor time.
  • The second check avoids an unlikely multithreading problem. A thread A could enter the lock and not finish before a thread B arrives. B has to wait in front of the lock. A exits the lock, now B enters the lock. Without the second check, B would now create a new instance. And this is, what we are trying to avoid.

 

using System;

namespace Singleton {

  public sealed class JustOne {
    private static readonly object _Lock = new object();
    private static JustOne _Instance = null;
    private JustOne() { }

    public static JustOne Instance {
      get {
        if (_Instance == null) {
          lock (_Lock) {
            if (_Instance == null) _Instance = new JustOne();
          }
        }
        return _Instance;
      }
    } //

    public new string GetHashCode() { return base.GetHashCode().ToString(); }
  } // class

  class Program {

    static void Main(string[] args) {
      JustOne A = JustOne.Instance;
      JustOne B = JustOne.Instance;
      Console.WriteLine("HashCode of object A: " + A.GetHashCode());
      Console.WriteLine("HashCode of object B: " + B.GetHashCode());      

      Console.ReadLine();
    } // main

  } // class
} // namespace
Advertisements

Prototype Pattern

Clonomat

Sometimes the creation of new objects is time and resource intensive. You could create a thousand objects during the program initialization and park them on a queue. The object would then be ready when needed. And looking at the Garbage Collection process in more detail, you may notice that the Generation has probably changed by then. Your object requires less processor time the older it becomes.

But this is not the topic today. It just has a similar idea. We are talking about time and/or resource intensive object creation.

The Prototype Pattern is used for cloning objects. Cloning can be substantially faster than initializing objects from scratch. Let’s say object A did load a lot of data from a file. You don’t have to do the same for object B. Simply copy object A and amend some fields.

Here is the pattern:

public interface IChocolateBar {
  IChocolateBar Clone();
} // interface

public class MintChocolateBar : IChocolateBar {
  public readonly int ObjectNumber;
  public MintChocolateBar(int xObjectNumber) { ObjectNumber = xObjectNumber; }

  public IChocolateBar Clone() { return MemberwiseClone() as MintChocolateBar; } 
} // class

public class DarkChocolateBar : IChocolateBar {
  public readonly int ObjectNumber;
  public DarkChocolateBar(int xObjectNumber) { ObjectNumber = xObjectNumber; }

  public IChocolateBar Clone() { return MemberwiseClone() as DarkChocolateBar; } 
} // class

public class CloneFactory {
  public IChocolateBar get(IChocolateBar xChocolateBar) { return xChocolateBar.Clone(); } 
} // class

The pattern is not really satisfying. Is there something better? C# offers the ICloneable interface.

public class Shortcut : ICloneable  {
  public readonly int ObjectNumber;
  public Shortcut(int xObjectNumber) { ObjectNumber = xObjectNumber; }

  public object Clone() { return MemberwiseClone(); } 
} // class

The problem with this interface is the missing generic type. In fact the use is obsolete and Microsoft does not recommend it anymore. We therefore build our own implementation.

public class Shortcut2 {
  public readonly int ObjectNumber;
  public Shortcut2(int xObjectNumber) { ObjectNumber = xObjectNumber; }

  public Shortcut2 ShallowCopy() { return MemberwiseClone() as Shortcut2; } 
} // class

Using an interface like

interface IShallowCopy<T> {
  T IShallowCopy();
} // interface 

public class Shortcut3<T> : IShallowCopy<T> {
  public readonly int ObjectNumber;
  public Shortcut3(int xObjectNumber) { ObjectNumber = xObjectNumber; }

  public T ShallowCopy() { return MemberwiseClone() as T; } 
} // class

is nonsense. You cannot compile and instantiate this.
What else could we do? A static clone method quickly leads us back to a factory similar type. Hence we end up with something that we were having at the very beginning today. Just keep your solutions generic and you should be fine with this pattern.

MemberwiseClone()

We were using MemberwiseClone() to keep the example source code simple. The following is important to know:

MemberwiseClone() is a shallow copy. If a field of the copied object is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

To avoid the same references in the clone, you have to write your own Deep Copy or Lazy Copy. Your clone method must clone the object and objects inside the object.

A practical example:

Stock exchange orders need to be sent with a minimal delay. The fight for nanoseconds is tremendous. Companies even shorten the physical server cables to the exchanges in order to increase speed. One foot in length equals roughly one nanosecond these days.
The object creation for orders takes too long in the proprietary business. It is meaningful to generate orders before any decision is made. The next order sits in a queue of clones. When the machine decides to trade, then the order is taken from that queue and a few fields are populated/overridden. These are eg. trade size and price. There is no memory allocation at this late stage. As said, each nanosecond counts.

Full source code

Notice that

Console.WriteLine("ObjectNumber = " + lMintClone.ObjectNumber); 

prints the same number as the original object. There are two objects at two locations in the RAM. Therefore the HashCode is different. Still the field content is the same.

using System;

namespace PrototypePattern {

  public interface IChocolateBar {
    IChocolateBar Clone();
  } // interface

  public class MintChocolateBar : IChocolateBar {
    public readonly int ObjectNumber;
    public MintChocolateBar(int xObjectNumber) { ObjectNumber = xObjectNumber; }

    public IChocolateBar Clone() { return MemberwiseClone() as MintChocolateBar; }

  } // class

  public class DarkChocolateBar : IChocolateBar {
    public readonly int ObjectNumber;
    public DarkChocolateBar(int xObjectNumber) { ObjectNumber = xObjectNumber; }

    public IChocolateBar Clone() { return MemberwiseClone() as DarkChocolateBar; }

  } // class

  public class CloneFactory {
    public IChocolateBar get(IChocolateBar xChocolateBar) { return xChocolateBar.Clone(); }
  } // class


  // IClonable is non-generic
  public class Shortcut : ICloneable {
    public readonly int ObjectNumber;
    public Shortcut(int xObjectNumber) { ObjectNumber = xObjectNumber; }

    public object Clone() { return MemberwiseClone(); } 
  } // class

  public class Shortcut2 {
    public readonly int ObjectNumber;
    public Shortcut2(int xObjectNumber) { ObjectNumber = xObjectNumber; }

    public Shortcut2 ShallowCopy() { return MemberwiseClone() as Shortcut2; } 
  } // class

  class Program {

    static void Main(string[] args) {
      CloneFactory lCloneFactory = new CloneFactory();
      MintChocolateBar lMint = new MintChocolateBar(1);
      MintChocolateBar lMintClone = lCloneFactory.get(lMint) as MintChocolateBar;
      Console.WriteLine("Original object: ");
      Console.WriteLine("HashCode = " + lMint.GetHashCode());
      Console.WriteLine("ObjectNumber = " + lMint.ObjectNumber);
      Console.WriteLine();
      Console.WriteLine("Clone: ");
      Console.WriteLine("HashCode = " + lMintClone.GetHashCode());
      Console.WriteLine("ObjectNumber = " + lMintClone.ObjectNumber);  // !!!
      Console.WriteLine();
      Console.WriteLine("Are the objects the same? " + (lMint == lMintClone));

      DarkChocolateBar lDark = new DarkChocolateBar(2);
      DarkChocolateBar lDarkClone = lCloneFactory.get(lDark) as DarkChocolateBar;
      Console.WriteLine();
      Console.WriteLine();
      Console.WriteLine();
      Console.WriteLine("Dark chocolate: ");
      Console.WriteLine("Are the objects the same? " + (lMint == lMintClone));


      // old school
      Shortcut lShort = new Shortcut(3);
      Shortcut lShortClone = lShort.Clone() as Shortcut;
      Console.WriteLine();
      Console.WriteLine("ICloneable: ");
      Console.WriteLine("Are the objects the same? " + (lShort == lShortClone));

      Console.ReadLine();
    } //

  } // class

} // namespace

example output:
Original object:
HashCode = 62125865
ObjectNumber = 1

Clone:
HashCode = 44200505
ObjectNumber = 1

Are the objects the same? False

Dark chocolate:
Are the objects the same? False

ICloneable:
Are the objects the same? False

Wikipedia

Builder Pattern

Car

Who does not know the StringBuilder in namespace System.Text?
The purpose of the StringBuilder is to construct a string much faster than using the operator overload “+”. Strings are immutable. Each time you use the overloaded operator, a new object is created. That slows down the creation of the final object. Here is a quick benchmark:

using System;
using System.Diagnostics;
using System.Text;

namespace demo {
  class Program {

    static void Main(string[] args) {
      Stopwatch lStopwatch = new Stopwatch();
      lStopwatch.Start();
      string s = "";
      for (int i = 0; i < 100000; i++) s += "x";
      lStopwatch.Stop();
      Console.WriteLine("Operator, elapsed ms: " + lStopwatch.ElapsedMilliseconds);

      StringBuilder lStringBuilder = new StringBuilder();
      lStopwatch.Restart();
      for (int i = 0; i < 100000; i++) lStringBuilder.Append("x");
      lStopwatch.Stop();
      Console.WriteLine("StringBuilder, elapsed ms: " + lStopwatch.ElapsedMilliseconds);

      Console.ReadLine();
    } //

  } // class
} // namespace

example output:
Operator, elapsed ms: 3029
StringBuilder, elapsed ms: 1

The StringBuilder supports method chaining. You can shorten your source code and write:

string s = new StringBuilder()
  .Append("a")
  .Append("b")
  .Append("c")
  .Append("d")
  .ToString();

instead of

StringBuilder lStringBuilder = new StringBuilder();
lStringBuilder.Append("a");
lStringBuilder.Append("b");
lStringBuilder.Append("c");
lStringBuilder.Append("d");
string s = lStringBuilder.ToString();

In general the purpose of a Builder is to separate complex object construction from its representation.

We leave the idea of strings behind and build something entirely different. This time it is not about speed, it is more about avoiding thousands of parameters in constructors and making complexity look a little bit easier. Two weeks ago I was using BMW AG to give an example for an Abstract Factory. Let’s stay loyal to cars and build classes for the production assembly.

using System;

namespace demo {

  [Flags]
  public enum eRadio { GPS = 1, MP3 = 2, Screen = 4, Phone = 8 }
  public enum eColor { NotSet = 0, Silver, Red, Blue, White, Black }

  class Program {

    public class Car {
      public readonly eRadio Radio;
      public readonly eColor Color;
      public readonly double Displacement;
      public readonly int Doors;
      public readonly bool Hatchback;
      public readonly bool LeatherSeats;

      internal Car(eRadio xRadio, eColor xColor, double xDisplacement, int xDoors, bool xHatchback, bool xLeatherSeats) {
        Radio = xRadio;
        Color = xColor;
        Displacement = xDisplacement;
        Doors = xDoors;
        Hatchback = xHatchback;
        LeatherSeats = xLeatherSeats;
      } // constructor

    } // class

    public class CarBuilder {

      private eRadio _Radio = 0;
      private eColor _Color = eColor.NotSet;
      private double _Displacement = 0.0;
      private uint _Doors = 1;
      private bool? _Hatchback = null;
      private bool? _LeatherSeats = null;

      internal CarBuilder SetColor(eColor xValue) { _Color = xValue; return this; }
      internal CarBuilder SetDisplacement(double xValue) { _Displacement = xValue; return this; }
      internal CarBuilder SetDoors(uint xValue) { _Doors = xValue; return this; }
      internal CarBuilder SetHatchback(bool xValue) { _Hatchback = xValue; return this; }
      internal CarBuilder SetRadio(eRadio xValue) { _Radio = xValue; return this; }
      internal CarBuilder SetLeatherSeats(bool xValue) { _LeatherSeats = xValue; return this; }
      internal Car Create() {
        if (_Hatchback == null) throw new Exception("Hatchback not set");
        if (_LeatherSeats == null) throw new Exception("LeatherSeats not set");
        if (_Doors < 1 || _Doors > 6) throw new Exception("number of Doors invalid");
        // ... etc.

        return new Car(_Radio, _Color, _Displacement, (int)_Doors, (bool)_Hatchback, (bool)_LeatherSeats);
      }
    } // class

    static void Main(string[] args) {

      Car lCar = new CarBuilder()
        .SetColor(eColor.Silver)
        .SetDisplacement(2.2)
        .SetDoors(5)
        .SetHatchback(true)
        .SetRadio(eRadio.GPS | eRadio.MP3 | eRadio.Screen)
        .SetLeatherSeats(true)
        .Create();

      Console.ReadLine();
    } // main

  } // class
} // namespace

http://en.wikipedia.org/wiki/Builder_pattern

Abstract Factory Pattern

BMW

 

There are many definitions on the internet of what the factory pattern would/should be. It is important to comply with your professor while you study at a university. Besides that programming is an art. It has nothing to do with naming conventions. Mona Lisa could be named Paul, you see. Only posh people care about technique naming. But if you paint a picture yourself, you don’t care about any technique naming convention at all; you only care about your results. And if people like it, then you are successful. It is the same with programming.

The Factory Method Pattern usually refers to a class that creates just one type of object.
The Abstract Factory Pattern usually refers to a class that can create various types of objects, which have something in common.

Besides that we have a lot of gibberish about some 10 and more years old pattern.

I could add a lot of code here, but it should suffice to just get the idea of it. Have a look at the above picture. An abstract class/interface is used as the base class for country specific factories. These factories create the objects.
The Z4 Model is built in Germany and China (just for demonstration purposes). Basically they are the same besides the difference between the Chinese and German regulations.

Now, translate that to your own business case. You may need a Factory that creates code for your Unix, Mac, and Windows system. On top of that you may have to create two distinct objects for your test and prod environment.

Other explanations are here or here.

Factory pattern

Factory

 

Life was so easy. Why do we have to make it worse now and implement a so-called “Factory”?

Dependency Injection is about using abstract classes and interfaces to avoid concrete classes. Therefore the creation of a concrete class like “new Ferrari()” violates the idea of flexibility and dependency injection. The Factory Pattern allows us to instantiate concrete classes while depending only on abstract classes/interfaces. The development process becomes much easier in an environment where concrete classes are changing frequently.

using System;

namespace demo {

  public abstract class Car { public string Name { get; protected set; } }
  public class Ferrari : Car { public Ferrari() { Name = "Red Speeder"; } }
  public class VW : Car { public VW() { Name = "German Classic"; } }
  public class Fiat : Car { public Fiat() { Name = "White Something"; } }

  public interface ICarFactory {
    Car GetObjectExpensive();
    Car GetObjectCheap();
  } // interface

  public class CarFactory : ICarFactory {
    public Car GetObjectExpensive() { return new Ferrari(); }
    public Car GetObjectCheap() { return new Fiat(); }
  } // class

  public class DependentClass {
    public readonly Car car = new Ferrari();
  } // class

  public class IndependentClass {
    public readonly Car car;
    public IndependentClass(Car xCar) {
      car = xCar;
    } // constructor
  } // class

  class Program {
    static void Main(string[] args) {
      DependentClass d = new DependentClass();
      CarFactory lCarFactory = new CarFactory();
      IndependentClass i = new IndependentClass(lCarFactory.GetObjectExpensive());
      Console.WriteLine(i.car.Name); // Red Speeder
      Console.ReadLine();
    } // main
  } // class

} // namespace

The code, which was dependent on the concrete class Ferrari, now only depends on the base class Car. You can easily inject any other car like VW or Fiat into your class. There is no need to search for all “new Ferrari()” commands in your code in case you need to change the type of car. It is all in one place. The dependency on the concrete class is gone.

We can increase the flexibility even further and use:

public interface ICarFactory {
  Car GetObject(string xType);    
} // interface

public class CarFactory : ICarFactory {
  public Car GetObject(string xType) {
    switch (xType) {
      case "Expensive": return new Ferrari();
      case "Average": return new VW();
      case "Cheap": return new Fiat();
      default: return null;
    }
  }
} // class

...
IndependentClass i = new IndependentClass(lCarFactory.GetObject("Expensive"));
...

The string can be replaced by an enum.

public enum eCar { Expensive, Average, Cheap };

public interface ICarFactory {
  Car GetObject(eCar xType);
} // interface

public class CarFactory : ICarFactory {
  public Car GetObject(eCar xType) {
    switch (xType) {
      case eCar.Expensive: return new Ferrari();
      case eCar.Average: return new VW();
      case eCar.Cheap: return new Fiat();
      default: return null;
    }
  } //
} // class

public class IndependentClass1 {
  public readonly Car car;
  public IndependentClass1(Car xCar) {
    car = xCar;
  } // constructor
} // class

public class IndependentClass2 {
  public readonly Car car;
  public IndependentClass2() {
    CarFactory lCarFactory = new CarFactory();
    car = lCarFactory.GetObject(eCar.Expensive);
  } // constructor
} // class

...
class Program {
  static void Main(string[] args) {
    DependentClass d = new DependentClass();
    CarFactory lCarFactory = new CarFactory();
    IndependentClass1 i1 = new IndependentClass1(lCarFactory.GetObject(eCar.Expensive));
    IndependentClass2 i2 = new IndependentClass2();
    Console.WriteLine(i2.car.Name); // Red Speeder
    Console.ReadLine();
  } // main
} // class

The Factory Pattern should only be used, when the need for it becomes great enough. Let’s say you are doing unit testing and you need to spoof the creator of an object. A Factory can be quite helpful then.
Factories add complexity to your code, so do not use them by default. They are conforming with Dependency Injection. Nevertheless, check the price you are willing to pay for independence.

Summary:

  • A factory method returns one of several possible classes that share an interface/abstract class/(parent class).
  • The class is chosen at runtime.
  • Before: Car c = new Ferrari(); After: Car c = lCarFactory.GetObject(eCar.Expensive);
  • Don’t use the Factory Pattern by default.