Thursday, May 10, 2012

Design Patterns - Singleton Pattern

Definition
Ensures a class has only one instance, and provides a global access to it.

Pattern examples
There are a few different approaches on how to implement the singleton pattern. I’ll show some in a C# environment.

Example 1 : “Lazy loading”.
By implementing lazy loading you insure that your class only gets instantiated when it is called upon for the first time and not earlier.

C# Code
/// <summary>
/// Singleton class. Lazy Loading. Instantiation only happens when the class is called upon for the first time.
/// Pitfall : Multithreading might result in ending up with 2 instances of the class. This implementation is not thread safe!

    /// </summary>
    public class MyLazySingleton
    {
        private static MyLazySingleton instance;

        /// <summary>
        /// Public static method that returns an instance of MyLazzySingleton
        /// </summary>
        /// <returns>Unique Instance of MyLazySingleton</returns>
        public static MyLazySingleton Instance()
        {
            //instantiate a new instance of the class if it is null
            if (instance == null)
                instance = new MyLazySingleton();
            return instance;
        }
    }

Pitfall
This piece of code is not ideal in a multithreading environment. Two instances can still be instantiated at the same time if both separate threads run over this code check:
//instantiate a new instance of the class if it is null
            if (instance == null)

Meaning, for both threads this check will be true and they will both instantiate an instance of that class, which is exactly what we want to prevent using the singleton pattern. Outside a multithreading environment this code works just fine. 

Example 2 : “Eagerly Creation”.

If the load is done at the start of the application or you are sure the class will get used for sure within your application, use eagerly creation of your singleton class. This is a thread safe implementation.

C# Code
/// <summary>
/// Singleton class. Eagerly Creation. Use this type of singleton if the load is done on startup or you are sure the singleton will be used
    /// at least once in your program. This implementation is thread safe!
    /// </summary>
    class MyEagerSingleton
    {
        /// <summary>
        /// Declare and instantiate immediatly
        /// </summary>
        private static MyLazySingleton instance = new MyLazySingleton();

        /// <summary>
        /// Public static method that returns an instance of MyEagerSingleton
        /// </summary>
        /// <returns>Unique Instance of MyEagerSingleton</returns>
        public static MyLazySingleton Instance()
        {
            return instance;
        }

No comments:

Post a Comment