Pages

Thursday, January 10, 2013

Design Patterns - Singleton

This pattern is very useful in scenarios where there should be only one instance of a certain class. Some frequent examples are classes representing a database connection or the logger used in a big application, which should be unique.

The key point of this design solution is that the constructor is private, so nobody can instantiate (although they can declare) objects of this type. However, the existence of only one instance of this class is assured by a static reference to only one object of this class, internally created.

This is how a singleton looks like implemented in Java:

class Singleton {
    private static Singleton theOneAndOnly;

    private Singleton();

    public Singleton getInstance() {
        if (theOneAndOnly == null) {
            theOneAndOnly = new Singleton();
        }
        return theOneAndOnly;
    }
    // other useful methods
}


As it can be noticed, the only way the single instance can be accessed is by using the getInstance() method. Inside this, the constructor is visible and, therefore, the unique object can be created for the first access.

A singleton cannot be subclassed because the constructor is declared private.

Another fact to remember is that starting with Java 6, the following alternative can be used to implement a singleton.



public enum Singleton {
    THEONEANDONLY; 

    // other useful methods
}

It is straightforward to check that conditions for being a singleton are verified: there is only one instance that can be accessed by classes outside of this class and the constructor is private, which means nobody can create a new instance.

No comments:

Post a Comment