Singleton pattern
From Wikipedia, the free encyclopedia
This article's external links may not follow Wikipedia's content policies or guidelines. Please improve this article by removing excessive or inappropriate external links. |
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. (This concept is also sometimes generalized to restrict the instance to a specific number of objects - for example, we can restrict the number of instances to five objects.) This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist. It is also considered an anti-pattern by some people, who feel that it is overused, introducing unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application. [1][2][3][4][5][6]
Contents |
[edit] Common uses
- The Abstract Factory, 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:
[edit] Class diagram
[edit] Implementation
Implementation of a singleton pattern must satisfy the single instance and global access principles. It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made protected (not private, because reuse and unit test could need to access the constructor). Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a singleton.
The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.
The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated.
[edit] Example implementations
[edit] Scala
The Scala programming language supports Singleton objects out-of-the-box. The 'object' keyword creates a class and also defines a singleton object of that type. As the concept is implemented natively, the design pattern to implement the concept is not required in this language.
object Example extends ArrayList { // creates a singleton called Example }
[edit] Java
The Java programming language solutions provided here are all thread-safe but differ in supported language versions and lazy-loading.
[edit] Traditional simple way
This solution is thread-safe without requiring special language constructs, but it may lack the laziness of the one below. The INSTANCE is created as soon as the Singleton class is initialized. That might even be long before getInstance() is called. It might be (for example) when some static method of the class is used. If laziness is not needed or the instance needs to be created early in the application's execution, or your class has no other static members or methods that could prompt early initialization (and thus creation of the instance), this (slightly) simpler solution can be used:
public class Singleton { public final static Singleton INSTANCE = new Singleton(); // Protected constructor is sufficient to suppress unauthorized calls to the constructor protected Singleton() {} }
Sometimes the static final field is made private and a static factory-method is provided to get the instance. This way the underlying implementation may change easily while it has no more performance-issues on modern JVMs.
[edit] The solution of Bill Pugh
This is a recommended method. It is known as the initialization on demand holder idiom and is as lazy as possible. Moreover, it works in all known versions of Java. This solution is the most portable across different Java compilers and virtual machines.
The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile and/or synchronized).
public class Singleton { // Protected constructor is sufficient to suppress unauthorized calls to the constructor protected Singleton() {} /** * SingletonHolder is loaded on the first execution of Singleton.getInstance() * or the first access to SingletonHolder.INSTANCE, not before. */ private static class SingletonHolder { private final static Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }
[edit] Java 5 solution
If and only if the compiler used is Java 5 (also known as Java 1.5) or newer, AND all Java virtual machines the application is going to run on fully support the Java 5 memory model, then (and only then) the volatile double checked locking can be used (for a detailed discussion of why it should never be done before Java 5 see The "Double-Checked Locking is Broken" Declaration):
public class Singleton { private static volatile Singleton INSTANCE; // Protected constructor is sufficient to suppress unauthorized calls to the constructor protected Singleton() {} private static synchronized Singleton tryCreateInstance() { if (INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } public static Singleton getInstance() { // use local variable, don't issue 2 reads (memory fences) to 'INSTANCE' Singleton s = INSTANCE; if (s == null) { //check under lock; move creation logic to a separate method to allow inlining of getInstance() s = tryCreateInstance(); } return s; } }
This example does not properly demonstrate the Double Checking issue since the constructor does not initialize anything. Allen Holub (in "Taming Java Threads", Berkeley, CA: Apress, 2000, pp. 176–178) notes that on multi-CPU systems (which are widespread as of 2009), the use of volatile may have an impact on performance approaching to that of synchronization, and raises the possibility of other problems. Thus this solution has little to recommend it over Pugh's solution described above...
[edit] The Enum-way
In the second edition of his book "Effective Java" Joshua Bloch claims that "a single-element enum type is the best way to implement a singleton"[8] for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.
public enum Singleton { INSTANCE; }
[edit] D
Singleton pattern in D programming language
import std.stdio; import std.string; class Singleton(T) { private static T instance; public static T opCall() { if(instance is null) { instance = new T; } return instance; } } class Foo { public this() { writefln("Foo Constructor"); } } void main(){ Foo a = Singleton!(Foo)(); Foo b = Singleton!(Foo)(); }
Or in this manner
// this class should be in a package to make private this() not visible class Singleton { private static Singleton instance; public static Singleton opCall() { if(instance is null) { instance = new Singleton(); } return instance; } private this() { writefln("Singleton constructor"); } } void main(){ Singleton a = Singleton(); Singleton b = Singleton(); }
[edit] PHP 5
Singleton pattern in PHP 5[9][10]:
<?php class Singleton { // object instance private static $instance; // The protected construct prevents instantiating the class externally. The construct can be // empty, or it can contain additional instructions... // This should also be final to prevent extending objects from overriding the constructor with // public. protected final function __construct() { ... } // The clone and wakeup methods prevents external instantiation of copies of the Singleton class, // thus eliminating the possibility of duplicate objects. The methods can be empty, or // can contain additional code (most probably generating error messages in response // to attempts to call). public function __clone() { trigger_error('Clone is not allowed.', E_USER_ERROR); } public function __wakeup() { trigger_error('Deserializing is not allowed.', E_USER_ERROR); } //This method must be static, and must return an instance of the object if the object //does not already exist. public static function getInstance() { if (!self::$instance instanceof self) { self::$instance = new self; } return self::$instance; } //One or more public methods that grant access to the Singleton object, and its private //methods and properties via accessor methods. public function doAction() { ... } } //usage Singleton::getInstance()->doAction(); ?>
[edit] Actionscript 3.0
Private constructors are not available in ActionScript 3.0 - which prevents the use of the ActionScript 2.0 approach to the Singleton Pattern. Many different AS3 Singleton implementations have been published around the web.
package { public class Singleton { private static var _instance:Singleton = new Singleton(); public function Singleton () { if (_instance){ throw new Error( "Singleton can only be accessed through Singleton.getInstance()" ); } } public static function getInstance():Singleton { return _instance; } } }
[edit] Objective-C
A common way to implement a singleton in Objective-C is the following:
@interface MySingleton : NSObject { } + (MySingleton *)sharedSingleton; @end @implementation MySingleton + (MySingleton *)sharedSingleton { static MySingleton *sharedSingleton; @synchronized(self) { if (!sharedSingleton) sharedSingleton = [[MySingleton alloc] init]; return sharedSingleton; } } @end
If thread-safety is not required, the synchronization can be left out, leaving the +sharedSingleton
method like this:
+ (MySingleton *)sharedSingleton { static MySingleton *sharedSingleton; if (!sharedSingleton) sharedSingleton = [[MySingleton alloc] init]; return sharedSingleton; }
This pattern is widely used in the Cocoa frameworks (see for instance, NSApplication
, NSColorPanel
, NSFontPanel
or NSWorkspace
, to name but a few).
Some may argue that this is not, strictly speaking, a Singleton, because it is possible to allocate more than one instance of the object. A common way around this is to use assertions or exceptions to prevent this double allocation.
@interface MySingleton : NSObject { } + (MySingleton *)sharedSingleton; @end @implementation MySingleton static MySingleton *sharedSingleton; + (MySingleton *)sharedSingleton { @synchronized(self) { if (!sharedSingleton) [[MySingleton alloc] init]; return sharedSingleton; } } +(id)alloc { @synchronized(self) { NSAssert(sharedSingleton == nil, @"Attempted to allocate a second instance of a singleton."); sharedSingleton = [super alloc]; return sharedSingleton; } } @end
There are alternative ways to express the Singleton pattern in Objective-C, but they are not always as simple or as easily understood, not least because they may rely on the -init
method returning an object other than self
. Some of the Cocoa "Class Clusters" (e.g. NSString
, NSNumber
) are known to exhibit this type of behaviour.
Note that @synchronized
is not available in some Objective-C configurations, as it relies on the NeXT/Apple runtime. It is also comparatively slow, because it has to look up the lock based on the object in parentheses. Check the history of this page for a different implementation using an NSConditionLock
.
[edit] C++
#include <iostream> using namespace std; /* Place holder for thread synchronization mutex */ class Mutex { /* placeholder for code to create, use, and free a mutex */ }; /* Place holder for thread synchronization lock */ class Lock { public: Lock(Mutex& m) : mutex(m) { /* placeholder code to acquire the mutex */ } ~Lock() { /* placeholder code to release the mutex */ } private: Mutex & mutex; }; class Singleton { public: static Singleton* GetInstance(); int a; ~Singleton() { cout << "In Dtor" << endl; } private: Singleton(int _a) : a(_a) { cout << "In Ctor" << endl; } static Mutex mutex; // Not defined, to prevent copying Singleton(const Singleton& ); Singleton& operator =(const Singleton& other); }; Mutex Singleton::mutex; Singleton* Singleton::GetInstance() { Lock lock(mutex); cout << "Get Inst" << endl; // Initialized during first access static Singleton inst(1); return &inst; } int main() { Singleton* singleton = Singleton::GetInstance(); cout << "The value of the singleton: " << singleton->a << endl; return 0; }
In the above example, the first call to Singleton::GetInstance
will initialize the singleton instance. This example is for illustrative purposes only; for anything but a trivial example program, this code contains errors.
[edit] C#
The simplest of all is:
public class Singleton { // The combination of static and readonly makes the instantiation // thread safe. Plus the constructor being protected (it can be // private as well), makes the class sure to not have any other // way to instantiate this class than using this member variable. public static readonly Singleton Instance = new Singleton(); // Protected constructor is sufficient to avoid other instantiation // This must be present otherwise the compiler provides a default // public constructor // protected Singleton() { } }
This example is thread-safe with lazy initialization. Note that the explicit static constructor which disables beforefieldinit. See http://www.yoda.arachsys.com/csharp/beforefieldinit.html
/// Class implements singleton pattern. public class Singleton { // Protected constructor is sufficient to avoid other instantiation // This must be present otherwise the compiler provides // a default public constructor protected Singleton() { } /// Return an instance of <see cref="Singleton"/> public static Singleton Instance { get { /// An instance of Singleton wont be created until the very first /// call to the sealed class. This is a CLR optimization that /// provides a properly lazy-loading singleton. return SingletonCreator.CreatorInstance; } } /// Sealed class to avoid any heritage from this helper class private sealed class SingletonCreator { // Retrieve a single instance of a Singleton private static readonly Singleton _instance = new Singleton(); //explicit static constructor to disable beforefieldinit static SingletonCreator() { } /// Return an instance of the class <see cref="Singleton"/> public static Singleton CreatorInstance { get { return _instance; } } } }
Example in C# 2.0 (thread-safe with lazy initialization) Note: This is not a recommended implementation because "TestClass" has a default public constructor, and that violates the definition of a Singleton. A proper Singleton must never be instantiable more than once. More about generic singleton solution in C#: http://www.c-sharpcorner.com/UploadFile/snorrebaard/GenericSingleton11172008110419AM/GenericSingleton.aspx
/// Parent for singleton /// <typeparam name="T">Singleton class</typeparam> public class Singleton<T> where T : class, new() { protected Singleton() { } private sealed class SingletonCreator<S> where S : class, new() { private static readonly S instance = new S(); //explicit static constructor to disable beforefieldinit static SingletonCreator() { } public static S CreatorInstance { get { return instance; } } } public static T Instance { get { return SingletonCreator<T>.CreatorInstance; } } } /// Concrete Singleton public class TestClass : Singleton<TestClass> { public string TestProc() { return "Hello World"; } } // Somewhere in the code ..... TestClass.Instance.TestProc(); .....
[edit] Delphi
As described by James Heyworth in a paper[11] presented to the Canberra PC Users Group Delphi SIG on 11/11/1996, there are several examples of the Singleton pattern built into the Delphi Visual Component Library. This unit demonstrates the techniques that were used in order to create both a Singleton component and a Singleton object:
unit Singletn; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs; type TCSingleton = class(TComponent) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TOSingleton = class(TObject) public constructor Create; destructor Destroy; override; end; var Global_CSingleton: TCSingleton; Global_OSingleton: TOSingleton; procedure Register; implementation procedure Register; begin RegisterComponents('Design Patterns', [TCSingleton]); end; { TCSingleton } constructor TCSingleton.Create(AOwner: TComponent); begin if Global_CSingleton <> nil then {NB could show a message or raise a different exception here} Abort else begin inherited Create(AOwner); Global_CSingleton := Self; end; end; destructor TCSingleton.Destroy; begin if Global_CSingleton = Self then Global_CSingleton := nil; inherited Destroy; end; { TOSingleton } constructor TOSingleton.Create; begin if Global_OSingleton <> nil then {NB could show a message or raise a different exception here} Abort else Global_OSingleton := Self; end; destructor TOSingleton.Destroy; begin if Global_OSingleton = Self then Global_OSingleton := nil; inherited Destroy; end; procedure FreeGlobalObjects; far; begin if Global_CSingleton <> nil then Global_CSingleton.Free; if Global_OSingleton <> nil then Global_OSingleton.Free; end; begin AddExitProc(FreeGlobalObjects); end.
[edit] Python
The desired properties of the Singleton pattern can most simply be encapsulated in Python by defining a module, containing module-level variables and functions. To use this modular Singleton, client code merely imports the module to access its attributes and functions in the normal manner. This sidesteps many of the wrinkles in the explicitly-coded versions below, and has the singular advantage of requiring zero lines of code to implement.
According to influential Python programmer Alex Martelli, The Singleton design pattern (DP) has a catchy name, but the wrong focus—on identity rather than on state. The Borg design pattern has all instances share state instead.[12] A rough consensus in the Python community is that sharing state among instances is more elegant, at least in Python, than is caching creation of identical instances on class initialization. Coding shared state is nearly transparent:
class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state # and whatever else is needed in the class -- that's all!
But with the new style class, this is a better solution, because only one instance is created:
class Singleton (object): def __new__(cls, *args, **kwargs): if not hasattr(cls, 'self'): cls.self = object.__new__(cls) return cls.self #Usage mySingleton1 = Singleton() mySingleton2 = Singleton() #mySingleton1 and mySingleton2 are the same instance. assert mySingleton1 is mySingleton2
Two caveats:
- The __init__-method is called every time Singleton() is called, unless cls.__init__ is set to an empty function.
- If it is needed to inherit from the Singleton-class, instance should probably be a dictionary belonging explicitly to the Singleton-class.
class InheritableSingleton (object): instances = {} def __new__(cls, *args, **kwargs): if InheritableSingleton.instances.get(cls) is None: cls.__original_init__ = cls.__init__ InheritableSingleton.instances[cls] = object.__new__(cls, *args, **kwargs) elif cls.__init__ == cls.__original_init__: def nothing(*args, **kwargs): pass cls.__init__ = nothing return InheritableSingleton.instances[cls]
To create a singleton that inherits from a non-singleton, multiple inheritance must be used.
class Singleton (NonSingletonClass, object): instance = None def __new__(cls, *args, **kargs): if cls.instance is None: cls.instance = object.__new__(cls, *args, **kargs) return cls.instance
Be sure to call the NonSingletonClass's __init__ function from the Singleton's __init__ function.
A more elegant approach using metaclasses was also suggested.[13]
class SingletonType(type): def __call__(cls): if getattr(cls, '__instance__', None) is None: instance = cls.__new__(cls) instance.__init__() cls.__instance__ = instance return cls.__instance__ # Usage class Singleton(object): __metaclass__ = SingletonType def __init__(self): print '__init__:', self class OtherSingleton(object): __metaclass__ = SingletonType def __init__(self): print 'OtherSingleton __init__:', self # Tests s1 = Singleton() s2 = Singleton() assert s1 assert s2 assert s1 is s2 os1 = OtherSingleton() os2 = OtherSingleton() assert os1 assert os2 assert os1 is os2
[edit] Perl
In a Perl version equal or superior to 5.10 a state variable can be used.
package MySingletonClass; use strict; use warnings; use 5.10; sub new { my ($class) = @_; state $the_instance; if (! defined $the_instance) { $the_instance = bless { }, $class; } return $the_instance; }
In older Perls, just use a closure.
package MySingletonClass; use strict; use warnings; my $THE_INSTANCE; sub new { my ($class) = @_; if (! defined $THE_INSTANCE) { $THE_INSTANCE = bless { }, $class; } return $THE_INSTANCE; }
If Moose is used, there is the MooseX::Singleton extension module.
[edit] Ruby
In Ruby, just include the Singleton in the class.
require 'singleton' class Example include Singleton end
[edit] ABAP Objects
In ABAP Objects, to make instantiation private, add an attribute of type ref to the class, and a static method to control instantiation.
program pattern_singleton. *********************************************************************** * Singleton * ========= * Intent * * Ensure a class has only one instance, and provide a global point * of access to it. *********************************************************************** class lcl_Singleton definition create private. public section. class-methods: get_Instance returning value(Result) type ref to lcl_Singleton. private section. class-data: fg_Singleton type ref to lcl_Singleton. endclass. class lcl_Singleton implementation. method get_Instance. if ( fg_Singleton is initial ). create object fg_Singleton. endif. Result = fg_Singleton. endmethod. endclass.
[edit] Prototype-based singleton
In a prototype-based programming language, where objects but not classes are used, a "singleton" simply refers to an object without copies or that is not used as the prototype for any other object. Example in Io:
Foo := Object clone Foo clone := Foo
[edit] Example of use with the factory method pattern
The singleton pattern is often used in conjunction with the factory method pattern to create a system-wide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Java Abstract Window Toolkit (AWT).
java.awt.Toolkit
is an abstract class that binds the various AWT components to particular native toolkit implementations. The Toolkit
class has a Toolkit.getDefaultToolkit()
factory method that returns the platform-specific subclass of Toolkit
. The Toolkit
object is a singleton because the AWT needs only a single object to perform the binding and the object is relatively expensive to create. The toolkit methods must be implemented in an object and not as static methods of a class because the specific implementation is not known by the platform-independent components. The name of the specific Toolkit
subclass used is specified by the "awt.toolkit" environment property accessed through System.getProperties()
.
The binding performed by the toolkit allows, for example, the backing implementation of a java.awt.Window
to bound to the platform-specific java.awt.peer.WindowPeer
implementation. Neither the Window
class nor the application using the window needs to be aware of which platform-specific subclass of the peer is used.
[edit] Drawbacks
It should be noted that this pattern makes unit testing far more difficult[14], as it introduces Global state into an application.
Advocates of Dependency Injection would regard this as an anti pattern, mainly due to its use of private and static methods.
In a nod to the concept of 'Code Smells', this pattern has also been known as the Stinkleton pattern. (coined by Robert Penner).
[edit] References
- ^ Alex Miller. Patterns I hate #1: Singleton, July 2007
- ^ Scott Densmore. Why singletons are evil, May 2004
- ^ Steve Yegge. Singletons considered stupid, September 2004
- ^ J.B. Rainsberger, IBM. Use your singletons wisely, July 2001
- ^ Chris Reath. Singleton I love you, but you're bringing me down, October 2008
- ^ http://googletesting.blogspot.com/2008/11/clean-code-talks-global-state-and.html
- ^ Gamma, E, Helm, R, Johnson, R, Vlissides, J: "Design Patterns", page 128. Addison-Wesley, 1995
- ^ Joshua Bloch: Effective Java 2nd edition, ISBN 978-0-321-35668-0, 2008, p. 18
- ^ McArthur, Kevin: "Pro PHP: Patterns, Frameworks, Testing and More", pp 22–23. Apress, 2008
- ^ Zandstra, Matt: "PHP Objects, Patterns and Practice", pp 147–149. Apress, 2008
- ^ Heyworth, James (1996-11-11). "Introduction to Design Patterns in Delphi". Canberra PC Users Group Delphi SIG (Objective Software Technology). http://www.obsof.com/delphi_tips/pattern.html#Singleton. Retrieved on 2008-01-19.
- ^ Alex Martelli. "Singleton? We don't need no stinkin' singleton: the Borg design pattern". ASPN Python Cookbook. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531. Retrieved on 2006-09-07.
- ^ Timur Izhbulatov. "Singleton in Python". timka.org - Programming. http://timka.org/programming/2008/12/17/singleton-in-python/. Retrieved on 2009-01-05.
- ^ http://googletesting.blogspot.com/2008/11/clean-code-talks-global-state-and.html
- "C++ and the Perils of Double-Checked Locking" Meyers, Scott and Alexandrescu, Andrei, September 2004.
- "The Boost.Threads Library" Kempf, B., Dr. Dobb's Portal, April 2003.
[edit] External links
- Singletons are Pathological Liars by Miško Hevery
- Java Singleton Design Pattern
- The "Double-Checked Locking is Broken" Declaration (Java)
- Java Singleton Pattern
- A Pattern Enforcing Compiler that enforces the Singleton pattern amongst other patterns
- Description from the Portland Pattern Repository
- Implementing the Singleton Pattern in C# by Jon Skeet
- A Threadsafe C++ Template Singleton Pattern for Windows Platforms by O. Patrick Barnes
- Implementing the Inheritable Singleton Pattern in PHP5
- Singleton Pattern and Thread Safety
- PHP patterns
- Javascript implementation of a Singleton Pattern by Christian Schaefer
- Singletons Cause Cancer by Preston Lee
- Singleton examples
- Article "Double-checked locking and the Singleton pattern" by Peter Haggar
- Article "Use your singletons wisely" by J. B. Rainsberger
- Article "Simply Singleton" by David Geary
- Article "Description of Singleton" by Aruna
- Article "Why Singletons Are Controversial"
- The Google Singleton Detector analyzes Java bytecode to detect singletons, so that their usefulness can be evaluated.
- Jt J2EE Pattern Oriented Framework
- Serialization of Singleton in Java
- Singleton at Microsoft patterns & practices Developer Center
- Using a Singleton variation (Registry) with FlashVars in actionscript 3
- Singleton Pattern in Cairngorm 2.1 with Actionscript 3
- More about Generic Singleton in C#: [1]
|