View RSS Feed

Hibernate

The Singleton pattern

Rating: 1 votes, 2.00 average.
by , 08-12-2011 at 04:29 AM (2410 Views)
In mathematics a singleton (not to be confused with a simpleton) is a set with exactly one element.
In computer science Singleton is a pattern which enforces the existence of only up to one instance of a class.

Singleton is sometimes considered an anti-pattern, and it's famous for being considered unnecessary in the world of Python (where you duck type).
Singleton is however useful, it is a nice and clean why to restrict the number of instances, to only one.
In addition if gives you a simple way to get the instance without checking if the has been created yet, it is created, if it has not been created yet, when you create it.

There is however a tendency amount people to make all classes Singleton as long as you do not need multiple instance, even in C#
where adding the modifier static to the class makes it constructorless, just like adding a private nullary (takes not arguments)
constructor [in Java too] as the only constructor. Making all classes Singleton is overkill, inflexible and makes the code extra messy,
when you just can make static methods and, optionally, add a private nullary constructor.

I recommend to use Singleton when and only when you need one instance, that is easily accessible in a simple/clean way, of the class,
and when that instance must exist, for example, when the instance is a window, not a façade or logic class, only(?) for graphical objects.


Java Code:
public final class YourClass //final is not required, it changes nothing because the only constructor is private
{
    /**
     * Singleton constructor
     */
    private YourClass() //There is a recommendation to use protected when working with JUnit (so you can use the constructor)
    {
        //Implement construction here
    }

    /**
     * Gets the only instance of this class
     *
     * @return  The only instance of this class
     */
    public static YourClass getInstance() //Use this method to get the instance of the class, instead of the constructor
    {
        if (onlyInstance == null)
            synchronized (YourClass.class)
            {
                if (onlyInstance == null)
                    onlyInstance = new YourClass();
            }

        return onlyInstance;
    }

    /**
     * The only instance
     */
    private static volatile YourClass onlyInstance = null;
}

Submit "The Singleton pattern" to Facebook Submit "The Singleton pattern" to Digg Submit "The Singleton pattern" to del.icio.us Submit "The Singleton pattern" to StumbleUpon Submit "The Singleton pattern" to Google

Updated 08-12-2011 at 06:13 PM by Hibernate (typo)

Tags: None Add / Edit Tags
Categories
Patterns

Comments