Common uses
Class diagramImplementationImplementation 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. Example implementationsScalaThe 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. object Example extends ArrayList { // creates a singleton called Example } JavaThe Java programming language solutions provided here are all thread-safe but differ in supported language versions and lazy-loading. The solution of Bill PughThis is the 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; } } Traditional simple wayJust like the one above, this solution is thread-safe without requiring special language constructs, but it lacks the laziness. The INSTANCE is created as soon as the Singleton class loads. 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, 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. Java 5 solutionIf 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() {} public static Singleton getInstance() { synchronized(Singleton.class) { if (INSTANCE == null) INSTANCE = new Singleton(); } return INSTANCE; } } Allen Holub (in "Taming Java Threads", Berkeley, CA: Apress, 2000, pp. 176–178) notes that on multi-CPU systems (which are widespread as of 2007), 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. The Enum-wayIn 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"[6] 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; } PHP 5Singleton pattern in PHP 5[7][8]: <?php class Singleton { // object instance private static $instance; // The private construct prevents instantiating the class externally. The construct can be // empty, or it can contain additional instructions... private function __construct() { ... } // The clone method prevents external instantiation of copies of the Singleton class, // thus eliminating the possibility of duplicate classes. The clone can be empty, or // it can contain additional code, most probably generating error messages in response // to attempts to call. private function __clone() { ... } //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(); ?> Actionscript 3.0Private 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. The common method is to use a hidden key of some sort. This is used to verify that the class is only instantiated by it's getInstance() method. An error exception is then thrown if the constructor is called by a external object. For example, in the implementation shown a private static function called "hidden" is used as the strict comparison key. This is only available to the Singleton class itself therefore ensuring that any attempts at exterior instantiation are canceled and an exception is thrown. package { public class Singleton { private static var _instance : Singleton = null; public function Singleton (h:Function) { if !(h === hidden) { throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" ); } } public static function getInstance() : Singleton { if(_instance == null) _instance = new Singleton(hidden); return _instance; } private static function hidden() : void {} } } Objective-CA 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 + (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, 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 Note that C++Here is a possible implementation in C++, using the Curiously Recurring Template Pattern. In this implementation, also known as the Meyers singleton [9], the singleton is a static local object. Because C++ provides no standard multithreading support, this solution is not thread-safe in general, though some compilers (e.g. gcc) generate thread-safe code in this case. #include <iostream> template<typename T> class Singleton { public: static T& Instance() { static T theSingleInstance; // assumes T has a protected default constructor return theSingleInstance; } virtual ~Singleton(); //a virtual destructor is needed if we need to execute //code in the derived class' destructor. }; class OnlyOne : public Singleton<OnlyOne> { friend class Singleton<OnlyOne>; int example_data; public: int Getexample_data() const {return example_data;} protected: OnlyOne(): example_data(42) {} // default constructor }; /* This test case should print "42". */ #include <iostream> int main() { std::cout << OnlyOne::Instance().Getexample_data()<<std::endl; return 0; } C++ (using pthreads)
A common design pattern for thread safety with the singleton class is to use double-checked locking. However, due to the ability of modern processors to re-order instructions (as long as the result is consistent with their architecturally-specified memory model), and the absence of any consideration being given to multiple threads of execution in the language standard, double-checked locking is intrinsically prone to failure in C++. There is no model — other than runtime libraries (e.g. POSIX threads, designed to provide concurrency primitives) — that can provide the necessary execution order.[1] By adding a mutex to the singleton class, a thread-safe implementation may be obtained. The following is an example of double-checked locking, and as such is prone to failure. #include <pthread.h> #include <memory> #include <iostream> class Mutex { public: Mutex() { pthread_mutex_init(&m, 0); } void lock() { pthread_mutex_lock(&m); } void unlock() { pthread_mutex_unlock(&m); } private: pthread_mutex_t m; }; class MutexLocker { public: MutexLocker(Mutex& pm): m(pm) { m.lock(); } ~MutexLocker() { m.unlock(); } private: Mutex& m; }; class Singleton { public: static Singleton& Instance(); int example_data; ~Singleton() { } protected: Singleton(): example_data(42) { } private: static std::auto_ptr<Singleton> theSingleInstance; static Mutex m; }; Singleton& Singleton::Instance() { if (theSingleInstance.get() == 0) { MutexLocker obtain_lock(m); if (theSingleInstance.get() == 0) { theSingleInstance.reset(new Singleton); } } return *theSingleInstance; } std::auto_ptr<Singleton> Singleton::theSingleInstance; Mutex Singleton::m; int main() { std::cout << Singleton::Instance().example_data << std::endl; return 0; } Note the use of the This implementation invokes the mutex-locking primitives for each call to More code must be written if the singleton code is located in a static library, but the program is divided into DLLs.citation needed Each DLL that uses the singleton will create a new and distinct instance of the singleton.citation needed To avoid that, the singleton code must be linked in a DLL. Alternatively, the singleton can be rewritten to use a memory-mapped file to store 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. /// 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(); /// Return an instance of the class <see cref="Singleton"/> public static Singleton CreatorInstance { get { return _instance; } } } } Another example(using static constructor) using System; using System.Threading; namespace Singleton1 { class Singleton { private static readonly Singleton _instance; private int v; /// Protected constructor is sufficient to prevent /// instantiation by using 'new' keyword. protected Singleton() { Console.WriteLine("Singleton Instance Creating..."); this.V = 0; Thread.Sleep(1000); // Simulate a HEAVY creation cost. Console.WriteLine("Singleton Instance Created."); } /// Static constructor static Singleton() { _instance = new Singleton(); } public static Singleton Instance { get { return _instance; } } public int V { get { return v; } set { v = value; } } public void DoSomeWork() { Console.Write("#"); lock(this) { V++; } Thread.Sleep(500); } } class TestClass { /// Singleton with Multithread static void Multithread() { Singleton instance = Singleton.Instance; Thread t = new Thread(new ThreadStart(instance.DoSomeWork)); t.Start(); } static void Main(string args) { int i; for(i = 0; i < 10; i++) { Console.WriteLine("Do some work..."); Thread.Sleep(100); } // ^- Until now, this application has no any singleton instance. -^ // for(i = 0; i < 300; i++) { // At first time, Singleton class make an instance of itself. // Other time, it will return absolutly same instance. Multithread(); } Thread.Sleep(1000); // Wait for sure all threads finished. Console.WriteLine(""); Console.WriteLine("V value - expected: {0}, actual: {1}",i,Singleton.Instance.V); // Singleton with 'new' is Strictly forbidden. // Singleton y = new Singleton(); // No acceptable. } } } 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. /// 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(); 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(); ..... PythonAccording 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.[10] 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): instance = None def __new__(cls, *args, **kwargs): if cls.instance is None: cls.instance = object.__new__(cls, *args, **kwargs) return cls.instance #Usage mySingleton1 = Singleton() mySingleton2 = Singleton() #mySingleton1 and mySingleton2 are the same instance. assert mySingleton1 is mySingleton2 Two caveats:
class InheritableSingleton (object): instances = {} def __new__(cls, *args, **kwargs): if InheritableSingleton.instances.get(cls) is None: cls.__original_init__ = cls.__init__ InheritableSingleton.instancescls = object.__new__(cls, *args, **kwargs) elif cls.__init__ == cls.__original_init__: def nothing(*args, **kwargs): pass cls.__init__ = nothing return InheritableSingleton.instancescls 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. PerlIn 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. RubyIn Ruby, just include the Singleton in the class. require 'singleton' class Example include Singleton end ABAP ObjectsIn 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.
Prototype-based singletonIn 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 Example of use with the factory method patternThe 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 Windowing Toolkit (AWT).
The binding performed by the toolkit allows, for example, the backing implementation of a References
External links
| | ||||||||||||||||