display | more...
The Singleton Pattern is defined in Design Patterns, Creational catagory. From Design Patterns:

Ensure a class only has one instance, and provides a global point of access to it.

A Singleton class will have a private or protected constructor and a class (static) access method, typically called instance or getInstance, that constructs and returns the object the first time called, and just returns the same instance on subsequent calls.

This pattern is useful when only one object of a particular classes may exist, and provides a single access point to that object. It is most flexible than using class (static) methods, because it allows the methods to be overriden by subclasses. Also, since the object is created on demand, the programmer doesn't have to explicitly ensure the object is created before it is used. This last point is particularly useful in languages like C++, where the order in which global variables are contructed is not controlled by the programmer.

The basic skeleton of a singleton:

class MySingleton {
    private static instance = null;

    private MySingleton() {
        // ...
    }

    public static MySingleton getInstance() {
        if (instance == null) {
            instance = new MySingleton();
        }
        return instance;
    }

    // use non-static public methods for rest of public interface
}

Log in or register to write something here or to contact authors.