Click here to Skip to main content
15,880,427 members
Articles / Programming Languages / C#

Design Patterns - A Deep Dive: Part 3

Rate me:
Please Sign up or sign in to vote.
2.00/5 (3 votes)
7 Jul 2008CPOL5 min read 24.3K   19   3
This article (Part 3) looks at one of the simplest and most commonly used types of Creational Design Patterns called the Singleton Design Pattern.

Introduction

Welcome to a series of articles on Design Patterns.

In the previous articles, we have covered the following areas:

  • Part 1 - looks at Design Patterns at a high level to understand what they can/can't do.
  • Part 2 - looks at the basic categorization of the patterns and a one-line definition of each pattern under that category.

The previous two parts have been a very high level overview of Design Patterns. The articles henceforth will concentrate on a single pattern, and hopes to provide an insight regarding coding the pattern, uses of that pattern, and some common gotcha's while using the pattern.

This article (Part 3) looks at one of the simplest and most commonly used type of Creational Design Pattern called the Singleton Design Pattern.

What is a Singleton Pattern?

An instance of a class is considered Singleton if it meets the following criteria:

  1. There is only one instance of the class during the lifetime of the application
  2. Any attempt to instantiate another instance of this class would return the previously created instance
  3. The constructor of this class is either private or protected only

Why is the Singleton Pattern classified as a Creational Pattern?

Creational Design Patterns are a category of Design Patterns in which there is some special process in the "creation" of an instance of a class.

In the case of the Singleton pattern, the constructor of the class is not accessible, and so an instance of that class cannot be created. The class will internally create an instance of itself and return a handle to this instance each time.

Due to this special behavior of the constructor, this pattern is classified as a Creational Pattern.

Let's talk code

Consider a simple class called Singleton which implements this pattern as shown:

C#
public class Singleton{
    private static Singleton m_INSTANCE = null;
    private Singleton(){}
    public static Singleton GetInstance(){
        if(m_INSTANCE == null)
            m_INSTANCE = new Singleton();
        return m_INSTANCE;
    }
}

The interesting features of this class are: the constructor, the method GetInstance(), and the private static Singleton type field m_INSTANCE, which we will get into more deeply in the following sections.

The constructor

The constructor of the Singleton class has been declared private. You could also declare it protected. Any other modifier like public or internal would allow a possibility to create an instance of this class, and would defeat the purpose of a Singleton.

C#
private Singleton(){}

The main concept to understand here is that we are restricting creating the instance of this class by setting the access modifier to the constructor. So now, no consumer of the class can create an instance of it. The only way we can get get an instance is to call the GetInstance() method and use that instance.

The field m_INSTANCE

The field m_INSTANCE is a private static field which will hold the object of the Singleton class.

C#
private static Singleton m_INSTANCE = null;

Since this field is lazy-initialized and the GetInstance() method always returns this object, we have been able to control the creation of instances for the Singleton class.

The GetInstance() method

The GetInstance() method is the only way we would be able to get an instance of the Singleton class.

C#
public static Singleton GetInstance(){
    if(m_INSTANCE == null)
        m_INSTANCE = new Singleton();
    return m_INSTANCE;
}

In the class shown above, we note that we are lazy-initializing the private static Singleton type field m_INSTANCE. This code ensures that there would be only one instance of the type, which will be created the first time the GetInstance() method is called. For any other call after this, the object stored in m_INSTANCE will be returned without creating a new instance.

The point to note about the GetInstance() method is that it has been declared public static with a return type of Singleton. As mentioned previously, since the constructor is private/protected, we will not be able to create an instance of the class, and so we will need this static method to get the instance.

Uses of the Singleton pattern

The Singleton pattern is extremely simple to implement and use. Typically, items which need to be initialized only once during the application life implement this pattern. Some of the common examples of such items can be: User Preferences and Settings, Thread/Connection pools, context objects, handle to Application Services (logging, data access, error handling etc.)

In short: "Singletons are most appropriate for services that do not change their nature based on their invocation context" (c2.com, 2008).

The bells and whistles

In this section, we will look at some interesting items which need to be kept in mind while using the Singleton pattern which might actually make it evil:

  1. Singletons vs. Global variables - In my opinion, while Singletons are a classes where we restrict creating multiple instances, global variables are more like "declared instances". Given this mindset, I would expect a global variable to be changed during the lifetime of an application based on certain conditions in the application, while a Singleton would remain in the same state. One more difference I note is that global variables are truly global to the application, but a Singleton could be accessible only to a part of the application/thread.
  2. Singletons and performance - One of the most important decisions while using a Singleton is when do we actually instantiate the members of the class and how expensive is it to keep this instance in memory? In the code sample shown previously, we had lazy initialized the m_INSTANCE member which was sufficient for that case. But given a more complex or expensive resource to create, we need to re-look at our design and check if it makes sense in having a Singleton or use some other mechanism.
  3. Singletons and state - One of the core concepts of Singletons is that they maintain their state as long as the application lasts. One of the drawbacks of this is that to load a different state (for example: running Unit Tests), we need to expose methods to set the new state, which quite defeats the idea that Singletons retain their state. The other alternative is to reload the application with a different state for the Singleton instance, but then is this acceptable for a Unit Test?

Wrap up

In this article, we have seen how a Singleton class can be created, and what its main elements are. I would love to hear your thoughts, ideas, and experiences using the Singleton Pattern. In the next article, we will look at another Creational Design Pattern.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
IT.Wox, always
India India
Sunny is the founder of IT.Wox, always (www.itwox.com) - a web application design, development & consulting company

Comments and Discussions

 
GeneralSuggestion.. Pin
Ranjan.D8-Jul-08 17:10
professionalRanjan.D8-Jul-08 17:10 
GeneralWhat about a lock-free method? Pin
supercat98-Jul-08 17:32
supercat98-Jul-08 17:32 
GeneralRe: Suggestion.. Pin
A Weatherill9-Jul-08 23:06
A Weatherill9-Jul-08 23:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.