Singleton pattern: Difference between revisions
→Implementation: Add a C++ example |
|||
Line 75: | Line 75: | ||
cls.__instance = object.__new__(cls, *args) |
cls.__instance = object.__new__(cls, *args) |
||
return cls.__instance |
return cls.__instance |
||
</syntaxhighlight> |
|||
=== C++ implementation === |
|||
As of [[C++11]], static local variable initialization is thread-safe and occurs after the first invocation.<ref>https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables</ref> |
|||
This is a safer alternative than a namespace or class-scope static variable. |
|||
<syntaxhighlight lang="cpp"> |
|||
class Singleton { |
|||
public: |
|||
static Singleton& GetInstance() { |
|||
// Allocate with `new` in case Singleton is not trivially destructible. |
|||
static Singleton* singleton = new Singleton(); |
|||
return *singleton; |
|||
} |
|||
private: |
|||
Singleton() = default; |
|||
}; |
|||
</syntaxhighlight> |
</syntaxhighlight> |
||
Revision as of 17:17, 2 June 2021
![](http://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/Singleton_UML_class_diagram.svg/220px-Singleton_UML_class_diagram.svg.png)
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the mathematical concept of a singleton.
Critics consider the singleton to be an anti-pattern in that it is frequently used in scenarios where it is not beneficial, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.[1][2][3][4]
Overview
The singleton[5] design pattern is one of the twenty-three well-known "Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
The singleton design pattern solves problems like:[6]
- How can it be ensured that a class has only one instance?
- How can the sole instance of a class be accessed easily?
- How can a class control its instantiation?
- How can the number of instances of a class be restricted?
- How can a global variable be accessed?
The singleton design pattern describes how to solve such problems:
- Hide the constructor of the class.
- Define a public static operation (
getInstance()
) that returns the sole instance of the class.
The key idea in this pattern is to make the class itself responsible for controlling its instantiation (that it is instantiated only once).
The hidden constructor (declared private or protected) ensures that the class can never be instantiated from outside the class.
The public static operation can be accessed easily by using the class name and operation name (Singleton.getInstance()
).
Common uses
- The abstract factory, factory method, builder, and prototype patterns can use singletons in their implementation.
- Facade objects are often singletons because only one facade object is required.
- State objects are often singletons.
- Singletons are often preferred to global variables because:
Anti-pattern considerations
The Singleton Pattern is generally considered an anti-pattern for the following reasons:
Singleton classes break object-oriented design principles
- It cannot be inherited from. To add new functionality, a new class cannot be descended to contain that functionality, breaking Separation of Concern.
- No control over creation. It is impossible to tell if a reference is of an existing instance or a new instance.
- Prevents dependency injection. As there is only a single instance of the class, a dependency cannot be injected into it. If done via a property, the dependency is changed for all references to that instance.
Singleton classes do not allow for test-driven development (TDD)
- As there is no control over creation, a "clean" instance of the object cannot be used for each test.
- Without dependency injection mock, objects cannot be used in tests.
Implementation
An implementation of the singleton pattern must:
- ensure that only one instance of the singleton class ever exists; and
- provide global access to that instance.
Typically, this is done by:
- declaring all constructors of the class to be private; and
- providing a static method that returns a reference to the instance.
The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. The following is a sample implementation written in Java.
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
Python implementation
class Singleton:
__instance = None
def __new__(cls, *args):
if cls.__instance is None:
cls.__instance = object.__new__(cls, *args)
return cls.__instance
C++ implementation
As of C++11, static local variable initialization is thread-safe and occurs after the first invocation.[7] This is a safer alternative than a namespace or class-scope static variable.
class Singleton {
public:
static Singleton& GetInstance() {
// Allocate with `new` in case Singleton is not trivially destructible.
static Singleton* singleton = new Singleton();
return *singleton;
}
private:
Singleton() = default;
};
C# implementation
public sealed class Singleton
{
public static Singleton Instance { get; } = new Singleton();
private Singleton() { }
}
In C# you can also use static classes to create singletons, where the class itself is the singleton.
public static class Singleton
{
public static MyOtherClass Instance { get; } = new MyOtherClass();
}
Unity Implementation
Singletons can be a useful tool when developing with Unity, due to the unique way classes are instantiated. This method is preferred over constructor hiding as it is possible to instantiate an object with a hidden constructor in Unity.
In order to prevent Instance from being overwritten, a check must be performed to ensure Instance is null. If Instance is not null, the GameObject containing the offending script should be destroyed.
If other components are dependant on the Singleton, the script execution order should be modified. This ensures that the component defining the Singleton is executed first.
class Singleton : MonoBehaviour
{
public static Singleton Instance { get; private set; }
private void Awake()
{
if (Instance != null && Instance != this) {
Destroy(this.gameObject);
} else {
Instance = this;
}
}
}
Note: It is also possible to implement by only removing the offending script, not the GameObject, by instead calling Destroy(this);
Lazy initialization
A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked. If the static method might be called from multiple threads simultaneously, measures may need to be taken to prevent race conditions that could result in the creation of multiple instances of the class. The following is a thread-safe sample implementation, using lazy initialization with double-checked locking, written in Java.[a]
public final class Singleton {
private static volatile Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Dart implementation
class Singleton {
Singleton._();
static Singleton get instance => Singleton._();
}
PHP implementation
class Singleton
{
private static $instance = null;
private function __construct() {}
public static function getInstance(): self
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
Java Implementation[8]
public class Coin {
private static final int ADD_MORE_COIN = 10;
private int coin;
private static Coin instance = new Coin(); // Eagerly Loading of singleton instance
private Coin(){
// private to prevent anyone else from instantiating
}
public static Coin getInstance() {
return instance;
}
public int getCoin() {
return coin;
}
public void addMoreCoin() {
coin += ADD_MORE_COIN;
}
public void deductCoin() {
coin--;
}
}
Kotlin Implementation[8]
Kotlin object keyword declares a singleton class[9]
object Coin {
private var coin: Int = 0
fun getCoin():Int {
return coin
}
fun addCoin() {
coin += 10
}
fun deductCoin() {
coin--
}
}
Delphi and Free Pascal implementation
GetInstance is thread safe implementation of Singleton.
unit SingletonPattern;
interface
type
TTest = class sealed
strict private
FCreationTime: TDateTime;
public
constructor Create;
property CreationTime: TDateTime read FCreationTime;
end;
function GetInstance: TTest;
implementation
uses
SysUtils
, SyncObjs
;
var
FCriticalSection: TCriticalSection;
FInstance: TTest;
function GetInstance: TTest;
begin
FCriticalSection.Acquire;
try
if not Assigned(FInstance) then
FInstance := TTest.Create;
Result := FInstance;
finally
FCriticalSection.Release;
end;
end;
constructor TTest.Create;
begin
inherited Create;
FCreationTime := Now;
end;
initialization
FCriticalSection := TCriticalSection.Create;
finalization
FreeAndNil(FCriticalSection);
end.
Usage:
procedure TForm3.btnCreateInstanceClick(Sender: TObject);
var
i: integer;
begin
for i := 0 to 5 do
ShowMessage(DateTimeToStr(GetInstance.CreationTime));
end;
Notes
- ^ In Java, to avoid the synchronization overhead while keeping lazy initialization with thread safety, the preferred approach is to use the initialization-on-demand holder idiom.[citation needed]
References
- ^ Scott Densmore. Why singletons are evil, May 2004
- ^ Steve Yegge. Singletons considered stupid, September 2004
- ^ Clean Code Talks - Global State and Singletons
- ^ Maximiliano Contieri. Singleton Pattern: The Root of all Evil, Jun 2020
- ^ a b Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 127ff. ISBN 0-201-63361-2.
{{cite book}}
: CS1 maint: multiple names: authors list (link) - ^ "The Singleton design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-16.
- ^ https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables
- ^ a b "Are you an Android Developer and not using Singleton Class yet?".
- ^ "Object declarations". Retrieved 2020-05-19.
External links
![]() | This article's use of external links may not follow Wikipedia's policies or guidelines. (November 2016) |
![](http://upload.wikimedia.org/wikipedia/commons/thumb/d/df/Wikibooks-logo-en-noslogan.svg/40px-Wikibooks-logo-en-noslogan.svg.png)
![](http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/30px-Commons-logo.svg.png)
- Complete article "Java Singleton Pattern Explained"
- Four different ways to implement singleton in Java "Ways to implement singleton in Java"
- Book extract: Implementing the Singleton Pattern in C# by Jon Skeet
- Singleton at Microsoft patterns & practices Developer Center
- IBM article "Double-checked locking and the Singleton pattern" by Peter Haggar
- IBM article "Use your singletons wisely" by J. B. Rainsberger
- Geary, David (April 25, 2003). "How to navigate the deceptively simple Singleton pattern". Java Design Patterns. JavaWorld. Retrieved 2020-07-21.
- Google article "Why Singletons Are Controversial"
- Google Singleton Detector (analyzes Java bytecode to detect singletons)