The Singleton Design pattern

What are design patterns

In the history of programming, there has been implementations of poorly written applications and excellent applications. The concept which separates the poor and good is identifying the common scenarios that show up in the code, and being able to implement the tested and best solution for the given programming scenario. This is what the core idea of design patterns is all about. They are a collection of rules to help you structure how your code should function with common programming problems. These design patterns have been put together from the good and major mistakes programmers have made. There’s no need of having to go through the pain of trying to implement something that’s full of design flaws, and spend the time trying to fix the errors generated.

The Singleton design pattern

The Singleton design pattern is just one of the many design patterns, but the singleton is used frequently and well know. The plain English definition of The Singleton design pattern is that it only allows one instantiation of an Object. Having two separate instances in your application should not be allowed. Below is an example of what a singleton would look like in C++:

#include <stddef.h>

class Singleton
{
public:
 static Singleton* Instance();

private:
 // Private so that it cannot be called
 // And only create a single instance of the class
 // using the Instance() function 
 Singleton() {};

 // Copy constructor
 Singleton(Singleton const&) {};

 // The assignment operator 
 Singleton& operator = (Singleton const&) {};

 static Singleton* m_pInstance;
};


// Global static pointer used to ensure a 
// Single instance of the class
Singleton* Singleton::m_pInstance = NULL;


Singleton* Singleton::Instance()
{
 // This will only allow one instance of the class
 // To get generated
 if(!m_pInstance)
 m_pInstance = new Singleton;

 return m_pInstance;
}
Share this post