Singing a singular design with Singleton

Now from my perspective there are a lot of programmers that finish school, get a degree, get a good job and then are presented with a problem. For example program designers design applications that include one of most simple design patterns.

Now I am not the best programmer in the world and also not the worst. Maybe I was lucky to be born in the era in which pattern design sprouted and started to grow. Also I know that most of you dear readers don’t need to reread this simple stuff, but if you are unsure of something … go ahead and take a peek. We will not tell ;)

This should be a first of design pattern series. So come back and check out the one of which you are unsure of.

The illusive Singleton

It is a design pattern that is used to control and restrict instantiation of a class to one and only one object. Simple, ehh? Why for God’s sake would you want to do that? Since this pattern is a creational pattern we use it when we need exactly one object to coordinate some events or actions across the whole system.

UML class diagram for Singleton software desig...
Image via Wikipedia

On the right we have a diagram in UML notation which shows how our singleton class should look like.

We can use this design pattern for instantiation of other design pattens1, to describe objects that describe states of the system, use them as a global reference to the instances of specific classes, because they don’t pollute the global namespace with unnecessary variables and they allow lazy allocation and initialization2.

When implementing singleton programmers must bare in mind that we need only one instance of the class and that instance requires global access principle. It is implemented by creating a class with a method that creates a new instance of the singleton class if one does not exist. If the instance already exists a reference to that object is returned. Implementation needs to make sure that no other classes can instantiate the class so usually constructor is hidden. When programming in multi-threaded applications and two threads access the creation method at the same time and the singleton instance does not yet exist, they should both check for an instance and only one should create the new instance. This is usually solved by using mutual exclusion on the class that indicated that the object is being instantiated.

For this example I will use Java

public class Singleton
{
   private static Singleton singleton;
   private Singleton() { }
   public static synchronized Singleton getInstance()
   {
     if (singleton == null)
     {
       singleton = new Singleton();
     }
     return singleton;
    }
}

And there you have it … The Java Singleton. Java not your thing, how about PHP?

class Singleton
{
  protected static $instance;
  private function __construct() { }
  private function __clone() { }
  public static function getInstance()
  {
    if (null === self::$_instance) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }
}

Still not satisfied ? How about python ?

class Singleton(object):
    def __new__(type):
        if not '_the_instance' in type.__dict__:
            type._the_instance = object.__new__(type)
        return type._the_instance

Maybe C++ ? The header file.

using namespace std;
class Singleton
{
public:
  static Singleton& GetInstance();
  ~Singleton();
private:
  Singleton();
  static Singleton * s_instance;
}

The source file.

Singleton * Singleton::s_instance = 0;
Singleton::Singleton() { }
Singleton::~Singleton()
{
  if (s_instance != 0)
  {
    delete s_instance;
  }
}
Singleton& Singleton::GetInstance()
{
  if (s_instance == 0)
  {
    s_instance = new Singleton();
  }
  return s_instance;
}

An that is all I can tell you about singing with Singletons. Hmm … wait not quite.

It should be noted that the singleton pattern, although simple to understand, does not get much love from the “gurus”. First of all it will make all the code depend on that class, meaning if a singleton class is changed all of the code that uses that class will be broken and has to be mended. Also since it uses private and static methods this pattern is sometimes seen as an anti pattern. Code can be difficult to unit test since the pattern introduces global state and unit tests need to be aware of that.

Next we will tackle the Factory patterns and see what we can manufacture with them. Till next time.

Reblog this post [with Zemanta]
  • Digg
  • StumbleUpon
  • Twitter
  • Facebook
  • MySpace
  • Google Bookmarks
  • del.icio.us
  • Reddit
  • Technorati
  1. Abstract Factory, Builder, Prototype to name a few []
  2. Global variables in some programming languages will be initialized at the start of the program and so consume unneeded resources []

You can follow any responses to this entry through the RSS 2.0 feed.

Support Us