Singleton Pattern   «Prev  Next»
Lesson 4Singleton: applicability
ObjectiveLearn when you should and should not use Singletons.

Applicability of the Singleton Design Pattern

The Singleton pattern has two primary criteria for applicability:
  1. The class should have exactly one instance which should be accessible from a method in the class.
  2. The class can be subclassed, and clients[1] can use the subclass as an instance of the superclass without having to change anycode.
The first criterion more or less defines the nature of the Singleton pattern.
The second criterion considers issues of reuse. In many cases there is more than one way to solve the immediate problem.

You choose your pattern more for how easily it can be modified within your system rather than for what it does.
The Singleton pattern is grouped with the other Creational patterns, although it is to some extent a non-creational pattern. There are any number of cases in programming where you need to make sure that there can be one and only one instance of a class. For example, your system can have only one window manager or print spooler, or a single point of access to a database engine. The easiest way to make a class that can have only one instance is to embed a static variable inside the class that we set on the first instance and check for each time we enter the constructor. A static variable is one for which there is only one instance, no matter how many instances there are of the class.
static boolean instance_flag = false;

The problem is how to find out whether creating an instance was successful or not, since constructors do not return values. One way would be to call a method that checks for the success of creation, and which simply returns some value derived from the static variable. This is inelegant and prone to error. However, because there is nothing to keep you from creating many instances of such non-functional classes and forgetting to check for this error condition.

A better way is to create a class that throws an Exception when it is instantiated more than once. Let us create our own exception class for this case:
class SingletonException extends RuntimeException{
  //new exception type for singleton classes
  public SingletonException(){
  public SingletonException(String s){

Note that other than calling its parent classes through the super()method, this new exception type does not do anything in particular. However, it is convenient to have our own named exception type so that the compiler will warn us of the type of exception we must catch when we attempt to create an instance of PrintSpooler.
[1] clients: Any object or class outside the pattern; generally one that only knows about the public interface the pattern and its classes present, rather than about its private implementation.