| advertise add site services publishers database health videos | ![]() | about toolbar stats live show health store more stuff JOIN/LOGIN |
Weight Loss Centre Singleton | Singleton Weight Loss Centre Directory |... goweightloss.com.au | Center:hair loss treatment, male pattern , female pattern hair... cosmeticsurgerypune.com | Pattern Maker | Ophthalmic Instrument | Pattern Maker Supplier croph.net | Specialists, Stephanie Dare Singleton,... arcfertility.com |
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces 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]
[edit] Common uses
[edit] Class diagram[edit] ImplementationImplementation 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] JavaThe Java programming language solutions provided here are all thread-safe but differ in supported language versions and lazy-loading. [edit] Traditional simple wayThis 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 { private static final Singleton INSTANCE = new Singleton(); // Private constructor prevents instantiation from other classes private Singleton() {} public static Singleton getInstance() { return INSTANCE; } } [edit] The solution of Bill PughUniversity of Maryland Computer Science researcher Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.[8] Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique is known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant 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. public class Singleton { // Private constructor prevents instantiation from other classes private 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 static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } } [edit] C++class CMySingleton { public: static CMySingleton& Instance() { static CMySingleton singleton; return singleton; } // Other non-static member functions private: CMySingleton() {}; // Private constructor CMySingleton(const CMySingleton&); // Prevent copy-construction CMySingleton& operator=(const CMySingleton&); // Prevent assignment }; [edit] C#/// <summary> /// Thread-safe singleton example created at first call /// </summary> public sealed class Singleton { private static Singleton instance; private static readonly Object mutex = new Object(); private Singleton() { } public static Singleton Instance { get { lock(mutex) return instance == null ? (instance = new Singleton()) : instance; } } } [edit] Objective Cstatic Singleton *sharedSingleton = nil; + (Singleton*)sharedManager { if (sharedSingleton == nil) { sharedSingleton = [[super allocWithZone:NULL] init]; } return sharedSingleton; } + (id)allocWithZone:(NSZone *)zone { return [self sharedManager]; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (NSUInteger)retainCount { return NSUIntegerMax; //denotes an object that cannot be released } - (void)release { //do nothing } - (id)autorelease { return self; } [edit] Rubyclass Klass include Singleton end [edit] Pythonclass Singleton(type): def __init__(cls, name, bases, dict): super(Singleton, cls).__init__(name, bases, dict) cls.instance = None def __call__(cls, *args, **kw): if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kw) return cls.instance class MyClass(object): __metaclass__ = Singleton print MyClass() print MyClass() [edit] Python (using decorators)def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class MyClass: ... [edit] PHPfinal class Singleton { protected static $_instance; protected function __construct() # we don't permit an explicit call of the constructor! (like $v = new Singleton()) { } protected function __clone() # we don't permit cloning the singleton (like $x = clone $v) { } public static function getInstance() { if( self::$_instance === NULL ) { self::$_instance = new self(); } return self::$_instance; } } $instance = Singleton::getInstance(); [edit] Flash ActionScriptpublic class Singleton { private static const INSTANCE:Singleton = new Singleton(); public function Singleton():void { if (INSTANCE != null) { //Flash forces constructors to be public //An error is thrown to prevent any new instances from being created. throw new Error("An instance of Singleton already exists."); } else { initialize(); } } private function initialize():void { trace("Singleton created"); } public static function get instance():Singleton { return INSTANCE; } } [edit] MATLABThe Singleton Pattern in object-oriented MATLAB is demonstrated in MATLAB Central File Exchange item Design Pattern: Singleton (Creational). This implementation is written in the new class-definition syntax introduced with MATLAB software version 7.6 (R2008a) [9] and uses a [edit] 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 [edit] 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 Window Toolkit (AWT).
The binding performed by the toolkit allows, for example, the backing implementation of a [edit] DrawbacksIt should be noted that this pattern makes unit testing far more difficult[6], 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. Some have suggested ways to break down the singleton pattern using methods such as reflection in languages such as Java.[10] [edit] References
[edit] External links
| |||||||||||||||||
| ↑ top of page ↑ | about thumbshots |