Generic Singleton

Click here for an introduction to the Singleton.

You might wonder the useful-ness of doing this.

Well, I found that by pure accident, I was reviewing some code then I decided to try enhance the original Singleton pattern.

Here are the benefits :

  • You don’t need to have a field or property representing the singleton instance,
  • With its syntax, it becomes somewhat clearer to read, as it focuses much on the singleton provider rather than the targetted class.
  • Last but not least, you won’t have to define anymore a singleton property in each class you want singleton-ed !

Well, if that’s not enough, I am listening to your suggestions and findings !

The syntax is cumbersome for your fingers but I found that the benefits are worth it.

using System;

namespace GenericSingleton
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Singleton<MyClass>.Instance.Text = "Hello";
            Singleton<MyClass>.Instance.Number = 123;

            Singleton<MyClass>.Instance.Text = "Good bye";
            Singleton<MyClass>.Instance.Number = 321;
        }
    }

    /// <summary>
    /// Provides a generic Singleton.
    /// </summary>
    /// <typeparam name="T">A <see cref="Type"/>.</typeparam>
    public abstract class Singleton<T> where T : new()
    {
        /// <summary>
        /// Instance backing-field.
        /// </summary>
        private static readonly T _instance = new T();

        /// <summary>
        /// Not publicly available.
        /// </summary>
        private Singleton()
        {
        }

        /// <summary>
        /// Singleton instance.
        /// </summary>
        public static T Instance
        {
            get { return _instance; }
        }
    }

    internal class MyClass
    {
        public int Number;
        public string Text;

        public void Do()
        {
        }
    }
}

Post a Comment

Your email is never shared. Required fields are marked *

*
*