| Computer Science Design Patterns Singleton | State |
The termSingleton refers to an object that can be instantiated only once.Use the Singleton Design pattern if:
In some applications, it is appropriate to enforce a single instance of an object, for example: window managers, print spoolers, database access, and filesystems.
In programming languages like Java, you have to create an instance of an object type (commonly called a Class) to use it throughout the code. Let's take for example this code:
Animaldog;// Declaring the object typedog=newAnimal();// Instantiating an object
This can also be written in a single line to save space.
Animaldog=newAnimal();// Both declaring and instantiating
At times, you need more than one instance of the same object type. You can create multiple instances of the same object type. Take for instance:
Animaldog=newAnimal();Animalcat=newAnimal();
Now that I have two instances of the same object type, I can use bothdog andcat instances separately in my program. Any changes todog would not effect thecat instance because both of them have been created in separate memory spaces. To see whether these objects actually are different we do something like this:
System.out.println(dog.equals(cat));// output: false
The code returnsfalse because both the objects are different. Contrary to this behavior, theSingleton behaves differently. A Singleton object type can not be instantiated yet you can obtain an instance of the object type. Let us create a normal object using Java.
classNormalObject{publicNormalObject(){}}
What we have done here is that we have created a class (object type) to identify our object. Within the braces of the class is a single method with the same name as that of the class (methods can be identified by the usage of parentheses at the end of their names). Methods that have the same name as that of the class and that do not have a return type are calledConstructors in OOP syntax. To create an instance of the class, the code can not be much simpler.
classTestHarness{publicstaticvoidmain(String[]args){NormalObjectobject=newNormalObject();}}
Note that to encourage the instantiation of this object, the constructor is called. The constructor as in this case can be called outside the class paranthesis and into another class definition because it is declared a public accessor while creating the Constructor in the above example.
Now we will create the Singleton object. You just have to change one thing to adhere to the Singleton design pattern: Make your Constructor's accessorprivate.
classSingletonObject{privateSingletonObject(){}}
Notice the constructor's accessor. This time around it has been declaredprivate. Just by changing it to private, you have applied a great change to your object type. Now you can not instantiate the object type. Go ahead try out the following code.
classTestHarness{publicstaticvoidmain(String[]args){SingletonObjectobject=newSingletonObject();}}
The code returns an error because private class members can not be accessed from outside the class itself and in another class. This way you have disabled the instantiation process for an object type. However, you have to find a way of obtaining an instance of the object type. Let's do some changes here.
classSingletonObject{privatestaticSingletonObjectobject;privateSingletonObject(){// Instantiate the object.}publicstaticSingletonObjectgetInstance(){if(object==null){object=newSingletonObject();// Create the object for the first and last time}returnobject;}}
The changes involve adding a static class field calledobject and apublic static method that can be accessible outside the scope of the class by using the name of the Class. To see how we can obtain the instance, lets code:
classTestHarness{publicstaticvoidmain(String[]args){SingletonObjectobject=SingletonObject.getInstance();}}
This way you control the creation of objects derived from your class. But we have still not unearthed the final and interesting part of the whole process. Try getting multiple objects and see what happens.
classTestHarness{publicstaticvoidmain(String[]args){SingletonObjectobject1=SingletonObject.getInstance();SingletonObjectobject2=SingletonObject.getInstance();}}
Unlike multiple instances of normal object types, multiple instances of a Singleton are all actually the same object instance. To validate the concept in Java, we try:
System.out.println(object1.equals(object2));// output: true
The code returnstrue because both object declarations are actually referring to the same object. So, in summarizing the whole concept, a Singleton can be defined as an object that can not be instantiated more than once. Typically it is obtained using a static custom implementation.
Java uses multi threading concept, to run/execute any program. Consider the class SingletonObject discussed above. Call to the method getInstance() by more than one thread at any point of time might create two instances of SingletonObject thus defeating the whole purpose of creating the singleton pattern. To make singelton thread safe, we have three options:1. Synchronize the methodgetInstance(), which would look like:
// Only one thread can enter and stay in this method at a timepublicsynchronizedstaticSingletongetInstance(){if(instance==null){instance=newSingleton();}returninstance;}
Synchronizing the method guarantees that the method will never be called twice at the same time. The problem with the above code is that 'synchronization' is expensive. 'Synchronization' checks will occur every time the function is called. Therefore, the above code should not be the first option.2. Another approach would be to create a singleton instance as shown below:
classSingletonObject{privatevolatilestaticSingletonObjectobject;privatefinalstaticObjectlockObj=newObject();// Use for lockingprivateSingletonObject(){// Exists only to avoid instantiation.}publicstaticSingletonObjectgetInstance(){if(object!=null){returnobject;}else{// Start a synchronized block, only one thread can enter and stay in the block one at a timesynchronized(lockObj){if(object==null){object=newSingletonObject();}}// End of synchronized blockreturnobject;}}}
The above code will be much faster; once the singleton instance is created no synchronization is needed. It just returns the same instance reference.3. Use static initialization block to create the instance. The JVM makes sure that the static block is executed once when the class is loaded.
classSingletonObject{publicfinalstaticSingletonObjectobject;static{...object=newSingletonObject();}privateSingletonObject(){// Exists only to avoid instantiation.}publicstaticSingletonObjectgetInstance(){returnobject;}}
In Java, the classjava.lang.Runtime is a singleton. Its constructor is protected and you can get an instance by calling thegetRuntime() method.
Beware of this design pattern! It creates the same issues than the global variables in procedural programming so it can be hard to debug.
It can be expensive. You may have to refactor all the instantiations of the class, unless the class is new.
There is no additional cost.
This pattern can be easily removed as automatic refactoring operations can easily remove its existence.
getInstance() to indicate the use of the pattern to the other developers.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.Singletons are declared just like classes except "object" replaces the keyword "class".
objectMySingleton{println("Creating the singleton")vali:Int=0}
This solution is thread-safe without requiring special language constructs:
publicclassSingleton{privatevolatilestaticSingletonsingleton;// volatile is needed so that multiple thread can reconcile the instanceprivateSingleton(){}publicstaticSingletongetSingleton(){// synchronized keyword has been removed from hereif(singleton==null){// needed because once there is singleton available no need to aquire monitor again & again as it is costlysynchronized(Singleton.class){if(singleton==null){// this is needed if two threads are waiting at the monitor at the time when singleton was getting instantiatedsingleton=newSingleton();}}}returnsingleton;}}
This technique 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 nested class is referenced when getInstance() is called making this solution thread-safe without requiring special language constructs.
publicclassSingleton{// Private constructor prevents instantiation from other classesprivateSingleton(){}/** * SingletonHolder is loaded on the first execution of Singleton.getInstance() * or the first access to SingletonHolder.INSTANCE, not before. */privatestaticclassSingletonHolder{privatestaticfinalSingletonINSTANCE=newSingleton();}publicstaticSingletongetInstance(){returnSingletonHolder.INSTANCE;}}
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" 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.
publicenumSingleton{INSTANCE;}
Singleton pattern in D programming language
importstd.stdio;importstd.string;classSingleton(T){privatestaticTinstance;publicstaticTopCall(){if(instanceisnull){instance=newT;}returninstance;}}classFoo{publicthis(){writefln("Foo Constructor");}}voidmain(){Fooa=Singleton!(Foo)();Foob=Singleton!(Foo)();}
Or in this manner
// this class should be in a package to make private this() not visibleclassSingleton{privatestaticSingletoninstance;publicstaticSingletonopCall(){if(instanceisnull){instance=newSingleton();}returninstance;}privatethis(){writefln("Singleton constructor");}}voidmain(){Singletona=Singleton();Singletonb=Singleton();}
Singleton pattern in PHP 5:
<?phpclassSingleton{// object instanceprivatestatic$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.protectedfinalfunction__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).publicfunction__clone(){trigger_error('Clone is not allowed.',E_USER_ERROR);}publicfunction__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.publicstaticfunctiongetInstance(){if(!self::$instanceinstanceofself){self::$instance=newself;}returnself::$instance;}// One or more public methods that grant access to the Singleton object, and its private// methods and properties via accessor methods.publicfunctiondoAction(){...}}// usageSingleton::getInstance()->doAction();?>
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{publicclassSingleton{privatestaticvar_instance:Singleton=newSingleton();publicfunctionSingleton(){if(_instance){thrownewError("Singleton can only be accessed through Singleton.getInstance()");}}publicstaticfunctiongetInstance():Singleton{return_instance;}}}
A common way to implement a singleton in Objective-C is the following:
@interfaceMySingleton :NSObject{}+(MySingleton*)sharedSingleton;@end@implementationMySingleton+(MySingleton*)sharedSingleton{staticMySingleton*sharedSingleton;@synchronized(self){if(!sharedSingleton)sharedSingleton=[[MySingletonalloc]init];returnsharedSingleton;}}@end
If thread-safety is not required, the synchronization can be left out, leaving the+sharedSingleton method like this:
+(MySingleton*)sharedSingleton{staticMySingleton*sharedSingleton;if(!sharedSingleton)sharedSingleton=[[MySingletonalloc]init];returnsharedSingleton;}
This pattern is widely used in the Cocoa frameworks (see for instance,NSApplication,NSColorPanel,NSFontPanel orNSWorkspace, 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.
@interfaceMySingleton :NSObject{}+(MySingleton*)sharedSingleton;@end@implementationMySingletonstaticMySingleton*sharedSingleton;+(MySingleton*)sharedSingleton{@synchronized(self){if(!sharedSingleton)[[MySingletonalloc]init];returnsharedSingleton;}}+(id)alloc{@synchronized(self){NSAssert(sharedSingleton==nil,@"Attempted to allocate a second instance of a singleton.");sharedSingleton=[superalloc];returnsharedSingleton;}}@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 thanself. 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.
The simplest of all is:
publicclassSingleton{// 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.publicstaticreadonlySingletonInstance=newSingleton();// Protected constructor is sufficient to avoid other instantiation// This must be present otherwise the compiler provides a default// public constructor//protectedSingleton(){}}
This example is thread-safe with lazy initialization.
/// Class implements singleton pattern.publicclassSingleton{//Use Lazy<T> to lazily initialize the class and provide thread-safe accessprivatestaticreadonlyLazy<Singleton>_lazyInstance=newLazy<Singleton>(()=>newSingleton());publicstaticSingletonInstance{get{return_lazyInstance.Value;}}privateSingleton(){}}
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>publicclassSingleton<T>whereT:class,new(){protectedSingleton(){}privatesealedclassSingletonCreator<S>whereS:class,new(){privatestaticreadonlySinstance=newS();//explicit static constructor to disable beforefieldinitstaticSingletonCreator(){}publicstaticSCreatorInstance{get{returninstance;}}}publicstaticTInstance{get{returnSingletonCreator<T>.CreatorInstance;}}}/// Concrete SingletonpublicclassTestClass:Singleton<TestClass>{publicstringTestProc(){return"Hello World";}}// Somewhere in the code.....TestClass.Instance.TestProc();.....
As described by James Heyworth in a paper 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:
unitSingletn;interfaceusesSysUtils,WinTypes,WinProcs,Messages,Classes,Graphics,Controls,Forms,Dialogs;typeTCSingleton=class(TComponent)publicconstructorCreate(AOwner:TComponent);override;destructorDestroy;override;end;TOSingleton=class(TObject)publicconstructorCreate;destructorDestroy;override;end;varGlobal_CSingleton:TCSingleton;Global_OSingleton:TOSingleton;procedureRegister;implementationprocedureRegister;beginRegisterComponents('Design Patterns',[TCSingleton]);end;{ TCSingleton }constructorTCSingleton.Create(AOwner:TComponent);beginifGlobal_CSingleton<>nilthen{NB could show a message or raise a different exception here}AbortelsebegininheritedCreate(AOwner);Global_CSingleton:=Self;end;end;destructorTCSingleton.Destroy;beginifGlobal_CSingleton=SelfthenGlobal_CSingleton:=nil;inheritedDestroy;end;{ TOSingleton }constructorTOSingleton.Create;beginifGlobal_OSingleton<>nilthen{NB could show a message or raise a different exception here}AbortelseGlobal_OSingleton:=Self;end;destructorTOSingleton.Destroy;beginifGlobal_OSingleton=SelfthenGlobal_OSingleton:=nil;inheritedDestroy;end;procedureFreeGlobalObjects;far;beginifGlobal_CSingleton<>nilthenGlobal_CSingleton.Free;ifGlobal_OSingleton<>nilthenGlobal_OSingleton.Free;end;beginAddExitProc(FreeGlobalObjects);end.
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. 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:
classBorg:__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:
classSingleton(object):def__new__(cls,*args,**kwargs):ifnothasattr(cls,'self'):cls.self=object.__new__(cls)returncls.self#UsagemySingleton1=Singleton()mySingleton2=Singleton()#mySingleton1 and mySingleton2 are the same instance.assertmySingleton1ismySingleton2
Two caveats:
classInheritableSingleton(object):instances={}def__new__(cls,*args,**kwargs):ifInheritableSingleton.instances.get(cls)isNone:cls.__original_init__=cls.__init__InheritableSingleton.instances[cls]=object.__new__(cls,*args,**kwargs)elifcls.__init__==cls.__original_init__:defnothing(*args,**kwargs):passcls.__init__=nothingreturnInheritableSingleton.instances[cls]
To create a singleton that inherits from a non-singleton, multiple inheritance must be used.
classSingleton(NonSingletonClass,object):instance=Nonedef__new__(cls,*args,**kargs):ifcls.instanceisNone:cls.instance=object.__new__(cls,*args,**kargs)returncls.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.
classSingletonType(type):def__call__(cls):ifgetattr(cls,'__instance__',None)isNone:instance=cls.__new__(cls)instance.__init__()cls.__instance__=instancereturncls.__instance__# UsageclassSingleton(object):__metaclass__=SingletonTypedef__init__(self):print'__init__:',selfclassOtherSingleton(object):__metaclass__=SingletonTypedef__init__(self):print'OtherSingleton __init__:',self# Testss1=Singleton()s2=Singleton()asserts1asserts2asserts1iss2os1=OtherSingleton()os2=OtherSingleton()assertos1assertos2assertos1isos2
In Perl version 5.10 or newer a state variable can be used.
packageMySingletonClass;usestrict;usewarnings;use5.010;subnew{my($class)=@_;state$the_instance;if(!defined$the_instance){$the_instance=bless{},$class;}return$the_instance;}
In older Perls, just use a global variable.
packageMySingletonClass;usestrict;usewarnings;my$THE_INSTANCE;subnew{my($class)=@_;if(!defined$THE_INSTANCE){$THE_INSTANCE=bless{},$class;}return$THE_INSTANCE;}
If Moose is used, there is theMooseX::Singleton extension module.
In Ruby, just include the Singleton module from the standard library into the class.
require'singleton'classExampleincludeSingletonend# Access to the instance:Example.instance
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.
To do: |
| Computer Science Design Patterns Singleton | State |