Search This Blog

Monday, May 3, 2010

What is a Singleton Pattern?


    Singleton Pattern belongs to the category of Creational Patterns. If you recall , the Creational Patterns are the subset of Design Patterns that encapsulate the logic of object creation. In a Singleton Pattern, there is a class (Singleton class) that ensures that only a single instance of itself can be created. It also provides a global point of access to this instance. So, irrespective of where in your code base this class is instantiated, you will always get access to the same instance.
    Let’s consider a real world example to make this concept clear. Consider an application that generates different types of reports using different methods. The Reporting class also has a counter that maintains the number of reports generated irrespective of method is used. This is a perfect example of a Singleton Pattern (we will implement the code later). When one is faced with a business problem like this, it’s really tempting to simply create an instance of the reporting class as a static global variable. Though this works, this does not guarantee that the instance of the class is created only once. In the Singleton pattern, the responsibility of ensuring that there is a single instance of the class lies on the Singleton class and not on the client that consumes the Singleton.