Singleton Design Pattern
Creational pattern. Creational design patterns are concerned with object creation.
Intent: "Ensure a class only has one instance, and provide a global point of access to it." [GoF]
Open in the interactive referenceDownload the PDF reference
Intent
The intent of the Singleton design pattern is to:
"Ensure a class only has one instance, and
provide a global point of access to it."
[GoF]
See Problem and Solution
sections for a more structured description of the intent.
-
The Singleton design pattern solves problems like:
- How can be ensured that a class has only one instance?
- How can the sole instance of a class be accessed globally?
-
For example, system objects that hold global data
(like database,
file system, printer spooler, or registry).
It must be ensured that such objects are instantiated only once within a system and that their sole instance can be accessed easily from all parts of the system. -
As a reminder:
Global data should be kept to a minimum (needed primarily by system objects).
In the object-oriented approach, "there is little or no global data." [GB07, p36]
Instead, data should be stored (encapsulated) in those objects that primarily work on it and passed (as parameter) to other objects if necessary.
Problem
The Singleton design pattern solves problems like:
How can be ensured that a class has only one instance?
How can the sole instance of a class
be accessed globally?
See Applicability section for all problems Singleton can solve.
See Solution section for how Singleton solves the problems.
-
The standard way is to
call the public constructor of a class
(
new Class1()) each time a new object is needed. - That's the kind of approach to avoid if we want to ensure that a class can be instantiated only once (has only one instance).
-
For example, system objects that hold global data
(like database,
file system, printer spooler, or registry).
[BGI]
It must be ensured that such objects are instantiated only once within a system and that their sole instance can be accessed easily from all parts of the system. -
For example, avoiding creating large numbers of unnecessary objects.
It should be possible to avoid creating unnecessary (duplicate, functionally equivalent) objects over and over again (to avoid excessive memory usage and system performance problems).
"It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed." [JB08, p20]
Background Information
-
Global data should be kept to a minimum
(needed primarily by system objects).
In the object-oriented approach, "there is little or no global data." [GB07, p36]
Instead, data should be stored (encapsulated) in those objects that primarily work on it and passed to other objects if necessary. -
A Registry is
"A well-known object that other objects can use to find common objects and services."
Registry (480) [MF03 ]
Solution
The Singleton design pattern provides a solution:
Hide the constructor of a class,
and define a static operation (getInstance())
that returns the sole instance of the class.
Describing the Singleton
design in more detail is the theme of the following sections.
See Applicability section for all problems Singleton can solve.
- The key idea in this pattern is to make a class itself responsible that it can be instantiated only once.
-
Hide the constructor of a class.
Declaring the constructor of a class private ensures that the class can neither be instantiated (from outside the class) nor subclassed (because subclasses need the constructor of their parent class).
"Enforce the singleton property with a private constructor or enum type" [JB08, Item 3] -
Define a static operation
(
getInstance()) that returns the sole instance of the class.
getInstance()is declared public and static.
A public static operation of a class is easy to access from anywhere within an application by using the class name and operation name (= global point of access):Singleton.getInstance().
Applicability
Design Problems
-
Creating Single Objects
- How can be ensured that a class has only one instance?
- How can the sole instance of a class be accessed globally?
-
Controlling Instantiation
-
How can a class control its instantiation?
-
How can the number of instances of a class
be restricted?
- How can creating large numbers of unnecessary objects be avoided?
-
How can a class control its instantiation?
Structure
Static Class Structure
-
Singleton-
(1) Defines an
INSTANCEconstant of typeSingletonthat holds the sole instance of the class. -
Fields declared
finalare initialized once and can never be changed. -
(2) Hides its constructor
(
private Singleton() {}). - This ensures that the class can never be instantiated from outside the class.
-
(3) Defines a static operation
(
getInstance()) for returning the sole instance of the class.
-
(1) Defines an
Consequences
Advantages (+)
-
Can control object creation.
- The getInstance operation can control the creation process, for example, to allow more than one instance of a class.
Disadvantages (–)
-
Makes clients dependent on the concrete
singleton class.
- This stops client classes from being reusable and testable.
- "Making a class a singleton can make it difficult to test its clients, as it's impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type." [JB08 , p17]
- See also Abstract Factory / Sample Code / Example 3 / Creating families of objects.
-
Can cause problems in a
multi-threaded environment.
- In multi-threaded applications, a singleton that holds mutable data (i.e., data that can be changed after the object is created) must be implemented carefully (synchronized).
Implementation
Implementation Issues
Variant 1: Subclassing not possible.
-
(1) The INSTANCE constant is set to the
instance of the class.
Fields declaredfinalare initialized once and can never be changed.
In Java, "Final fields also allow programmers to implement thread-safe immutable objects without synchronization." [JLS12 , 17.5 Final Field Semantics] -
(2) The constructor of the class is
hidden (declared
private).
This ensures that the class can neither be instantiated (from outside the class) nor subclassed (subclasses need/call the constructor of their parent class). -
(3) The public static
getInstance()operation returns the INSTANCE constant.
Clients can access the sole instance easily by callingSingleton.getInstance(). - See also Flyweight and State / Sample Code.
Variant 2: Subclassing possible.
-
(1) The
instancefield holds the instance of a subclass. -
(2) Singleton's default constructor is used.
Because the class is abstract, it can't be instantiated. -
(3) The public static final
getInstance()operation must decide which subclass to instantiate. This can be done in different ways: according to user input, system environment, configuration file, etc.
Note that operations declaredfinalcan't be redefined by subclasses. - See also Abstract Factory / Sample Code / Example 3 / Creating families of objects.
Sample Code 1
Basic Java code for implementing the sample UML diagram.
1 package com.sample.singleton.basic;
2 public class MyApp {
3 public static void main(String[] args) {
4 Singleton ref1 = null, ref2 = null;
5 ref1 = Singleton.getInstance();
6 ref2 = Singleton.getInstance();
7 if (ref1 == ref2) {
8 // The two singleton references are identical.
9 System.out.println("Singleton instantiated only once.");
10 }
11 }
12 }
Singleton instantiated only once.
1 package com.sample.singleton.basic;
2 public class Singleton {
3 // (1) INSTANCE constant that holds the sole instance.
4 private static final Singleton INSTANCE = new Singleton();
5 // (2) Private (hidden) constructor.
6 private Singleton() { }
7 // (3) Static operation that returns the sole instance.
8 public static Singleton getInstance() {
9 return INSTANCE;
10 }
11 }
Not included on this page: Motivation. See the GoF Design Patterns Reference (PDF) for the complete description.