The Singleton pattern !

UPDATE : I have created a generic Singleton.

For the first programming related post, it is going to be a simple post.

The Singleton pattern,

What is this ?

If you are familiar with programming, you probably know what this is, if you are new to programming, i’ll try to explain it to you, especially what it can do for you.

The Singleton pattern, as defined in Wikipedia : “In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object.”

That is, when getting more comfortable with programming, you start to shape your own coding style, by creating some kind of architectures. However, there might be some times when you are confronted to some design issues. (e.g. What you coded doesn’t do what exactly what you expected when thinking about it in your brain)

Still here ?

The Singleton Pattern allows to have a unique instance of a class throughout your application.

Why do I need this ?

Here is one example I encountered when developing my DJ-ing software. Beside the business logic of my application, I had to use a library for accessing audio hardware that is inside my computer : program my sound card to fit my needs. We are going to call this thing the audio manager.

From a development perspective, you need to have a unique and instance of that thing because as it is said on the title it is a manager, hence, it manages one or more thing(s). So when you want to access your audio card, you generally want exclusive access to it. There could be some undesired behaviour if two “things” wants to access an audio device. Moreover, you like to have a unique access point for working with your audio card. This is where the Singleton comes in handy, a unique instance of an object, taking care of not creating other (duplicate) instances of it, returning the first instance created. (Just like in real life, there is one instance of a manager and multiple instances of employees :-)

This is a very common pattern in software development.

Talking .NET now, the implementation is as follows :

You declare the class constructor as private or protected, (we are going to use private for now) this is what blocks the process of creating a new (copy) object of it. You declare a static property in this class, which is nothing more than a instance of the class itself. The static field will be initialized inline and declared as readonly.

This way of coding offers you this :

  • By declaring it as static, you don’t have to create an instance of it, you can just call Singleton.Instance, the instance is available without creating a new object because it is declared as static. Now the readonly keyword does not allow you to modify it once your program has initialized.

The readonly shall not be used without creating a new object of the class :


using System;

namespace PatternSingletonApplication
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var instance = Singleton.Instance;
            var instance1 = Singleton.Instance;

            // Test if it is the same instance.
            if (instance == instance1)
                Console.WriteLine("'instance' and 'instance1' are the same instance.");

            Console.WriteLine("Singleton.Instance can also be accessed directly,");
            Console.WriteLine(Singleton.Instance.Test());

            Console.ReadKey();
        }
    }

    public class Singleton
    {
        /// <summary>
        /// Protected because we don't want to expose it except for derived classes.
        /// </summary>
        protected Singleton() { }

        /// <summary>
        /// The unique instance of the class.
        /// </summary>
        public static readonly Singleton Instance = new Singleton();

        /// <summary>
        /// Added methods shall not be static then !
        /// </summary>
        /// <returns></returns>
        public string Test()
        {
            return "Hello from Instance.Test !";
        }
    }
}

Design Patterns beginners should consider Design Patterns in C# and VB.NET – Gang of Four (GOF). I have it and it’s great, there are nearly 70 samples showing the implementation of (all existing ?) design patterns. For about 70€ for all this, that’s cool, no ?

Moreover, this products offers :

  • Structural examples
  • Real-world examples
  • .NET optimized examples

(Note that I have no affiliation with the site mentioned above)


Post a Comment

Your email is never shared. Required fields are marked *

*
*