Intent: Ensure that a class has one instance, and provide a global point of access to it.
Almost every programmer has encountered this problem and formulated an approach for solving it in a general way - some solutions are better than others. The solution offered by GoF (Gang of Four) would look something like the following when coded in Java.
public class Singleton { private static Singleton instance = null; public static Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } private Singleton() { ... } // possibly another constructor form public void someMethod() { ... } // ... other methods }
The programmer would access the single instance of this class by writing something similar to
Singleton.getInstance().someMethod()
or similar to
Singleton s = Singleton.getInstance();
s.method1();
...
s.method2();
...
For a more complete discussion of the Singleton pattern, see the chapter "Singleton" in the book Design Patterns: Elements of Reusable Object-Oriented Software by the "Gang of Four" Gamma et al., or the chapter "Singleton" in the book Patterns in Java by Mark Grand. For information about variations on the Singleton Pattern, see the chapter entitled "To Kill a Singleton" in the book Pattern Hatching: Design Patterns Applied by John Vlissides or the article "Implementing the Singleton Pattern in Java" by Rod Waldhoff.
For discussion re: using Singleton for multi-threaded applications, click here