Blog Archives

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

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

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.