Factory Pattern

What is the Factory Method Pattern?

Wikipedia describes it as:

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.


The Factory Pattern moves and abstracts implementation details of similar classes or even a single class or struct that has many ways to implement or instantiate it and doesn’t require the user of that object to know about all the dependencies or how to construct it.

If the requirements for creating an object changed, and you were manually creating that object all over your application, you would have to update all usages of it if there was ever a change. Instead, leave that work up to the class that is building the object for you. Define a separate operation/method for creating the object/s.

This also enables us to create subclasses that can redefine how an object is created or even which subtype to instantiate.

Creating an object often requires complex processes not appropriate to include within a composing object. The object’s creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object’s concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.


Let’s look at a simple example where we have a struct similar to .NETs TimeSpan object. It is just going to hold a number of ticks, but we may want to build up this Duration wrapper from several different lengths or units.

Examples are in C#.

public struct MyDuration {
  private readonly long ticks;
  public long Ticks { get { return ticks; } }

  // public MyDuration(long ticks) {
  //   this.ticks = ticks;
  // }

  private MyDuration(long ticks) {
    this.ticks = ticks;
  }

  public static MyDuration FromTicks(long ticks) {
    return new MyDuration(ticks);
  }

  public static MyDuration FromMilliseconds(long milliseconds) {
    return new MyDuration(milliseconds * 10000);
  }

  public static MyDuration FromSeconds(long seconds) {
    return new MyDuration(seconds * 10000 * 1000);
  }
}

public void main() {
  MyDuration duration = MyDuration.FromSeconds(5);
  // duration.Ticks == 50000000
}

You will also notice that I used a private constructor. Mixing the Factory Pattern with a traditional constructor can be confusing.

new MyDuration(5) //What does that mean?

Instead, use a private constructor, and use the same pattern for all use cases.

C#6 allows us to use named parameters, but I still like to lean towards consistency.

new MyDuration(ticks: 5)

Reminder, Pluralsight has many courses on different design patterns in many different languages and implementations, and they have a FREE trial!

Start a 10-day free trial at Pluralsight

Singleton Pattern

What is the Singleton Pattern?

Wikipedia describes it as:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.


Sometimes this is because we need shared state across the application, or for efficiency reasons – maybe for I/O operations. There are heavy debates on when or if you should even try to do this, but there are definitely use cases. Be careful when you have data/properties that need to be shared across a system through single instantiation, it may be a code smell. If it is what you need, here are some implementation details.

The biggest problems you are going to run into while implementing this pattern is thread safety. Let’s look a very straightforward, basic implementation of the Singleton.

Reminder, Pluralsight has many courses on different design patterns in many different languages and implementations, and they have a FREE trial!

Start a 10-day free trial at Pluralsight

Examples are in C#.

 public class Singleton {
  private static Singleton instance;
  private Singleton() {
    // Things that must only happen once
  }
  public static Singleton Instance() {
    if (instance == null)
    {
      instance = new Singleton()
    }
    return instance;
  }
  public void DoSomething() {
    // Must be thread safe
  }
}

We may run into threading issues where two threads try to access the constructor at the same time.


We could do some craziness like doing explicit thread locking and double checking.

 public class Singleton {
  private static Singleton instance;
  private static readonly object mutex = new object();
  private Singleton() {
    // Things that must only happen once
  }
  public static Singleton Instance() {
    if (instance == null) {
      lock (mutex) {
        if (instance == null)
        {
          instance = new Singleton()
        }
      }
    }
    return instance;
  }
  public void DoSomething() {
    // Must be thread safe
  }
}

Unless your class is very IO heavy or doing other heavy lifting, you probably won’t run into huge performance costs by thread locking, but it still isn’t very pretty, and can cause it’s own problems.


By understanding the mechanics of static classes and their static constructor, we can understand that .NET does a pretty good job of only letting one thread inside of a static constructor at a time, so an empty static constructor solves a lot of our problems and even forces a certain level of laziness in instantiation, but isn’t perfect.

static Singleton() {}

If being lazy is super important to you, you can go the extra mile and create an internal holder for your singleton.

 public class Singleton {
  private static class SingletonHolder {
    internal static readonly Singleton instance = new Singleton();
    // Empty static constructor forces laziness
    static SingletonHolder() {}
  }
  private Singleton() { Console.WriteLine("Instantiate") }
  public static Singleton Instance { get { return SingletonHolder.instance; } };
  // Stateless method
  public void SayHi() {
    Console.WriteLine("Hello");
  }
}

// Example usage
public void main() {
  Singleton.SayHi();
  Console.WriteLine("Before Usage");
  Singleton s = Singleton.Instance;

  /*
    Output:
    Hello
    Before Usage
    Instantiate
  */
}

In this example, simple methods that don’t need access to the internal state that you are trying to share across the application, don’t even need an instance of the class to execute and will not instantiate the class until you actually ask for the instance.


In .NET4 and later, you can use built-in language features to get real lazy implementation.

 public class Singleton {
  private static readonly Lazy lazyInstance =
    new Lazy(() => new Singleton(), isThreadSafe: true)
  private Singleton() {}
  public static Singleton Instance { get { return instance.Value; } };
  public void SayHi() {}
}