The Singleton Pattern: "One of A Kind Objects"
The Singleton Pattern: "One of A Kind Objects"
The Singleton Pattern: "One of A Kind Objects"
OneofaKindObjects
Whatisthis?
Singleton:Howtoinstantiatejustoneobjectoneandonlyone!
Why?
Manyobjectsweneedonlyoneof:threadpools,caches,dialogboxes,
objectsthathandlepreferencesandregistrysettingsetc.
Ifmorethanoneinstantiated:
Incorrectprogrambehavior,overuseofresources,inconsistentresults
Alternatives:
Useaglobalvariable
Downside:assignanobjecttoaglobalvariablethenthatobjectmightbe
createdwhenapplicationbegins.Ifapplicationneverendsupusingitand
objectisresourceintensive>waste!
Useastaticvariable
Downside:howdoyoupreventcreationofmorethanoneclassobject?
TheLittleSingleton
Howwouldyoucreateasingleobject?
new MyObject ( );
Andwhatifanotherobjectwantedtocreatea
MyObject?CoulditcallnewonMyObject
again?
Yes.
Canwealwaysinstantiateaclassoneormore
times?
Yes.Caveat:Onlyifitispublicclass
Andifnot?
Onlyclassesinthesamepackagecaninstantiateit
buttheycaninstantiateitmorethanonce.
Isthispossible?
public MyClass {
private MyClass ( ) { }
}
Whatdoesitmean?
Yes.Itisalegaldefinition
Aclassthatcantbeinstantiatedbecauseit
hasaprivateconstructor
TheLittleSingleton(contd.)
Isthereanyclassthatcoulduseaprivateconstructor?
Whatsthemeaningofthefollowing?
public MyClass {
public static MyClass getInstance ( ) { }
}
Instantiatingaclasswithaprivateconstructor:
public MyClass {
private MyClass ( ) { }
public static MyClass getInstance ( ) { }
}
TheClassicSingletonPattern
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables
Constructor is
declared private;
only singleton can
instantiate this
class!
private Singleton ( ) { }
public static Singleton getInstance ( ) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton
( );
}
return uniqueInstance;
}
Of course, Singleton is a
regular class so it has other
useful instances and
methods.
We have a static
variable to hold
our one instance
of the class
Singleton.
CodeUpClose
uniqueInstance holds our ONE
instance; remember it is a static
variable
if (uniqueInstance == null) {
uniqueInstance = new Singleton ( );
}
return uniqueInstance;
If uniqueInstance wasnt null, then it was
previously created. We just fall through
to the return statement. In either case,
we have an instance and we return it.
instantiation.
SingletonPatternDefined
TheSingletonPatternensuresaclasshasonlyoneinstance,and
providesaglobalpointofaccesstoit.
The getInstance ( ) method
is static, which means it is a
class method, so you can
conveniently access this
method anywhere in your
code using
Singleton.getInstance ( ).
Thats just as easy as
accessing a global variable,
but we get benefits like lazy
instantiation from the
Singleton.
Singleton
static uniqueInstance
// other useful variables
static getInstance ( )
// other methods
Summary
TheSingletonPatternensuresyouhaveatmostone
instanceofaclassinyourapplication
TheSingletonPatternalsoprovidesaglobalaccess
pointtothatinstance.
JavasimplementationoftheSingletonPatternmakes
useofaprivateconstructor,astaticmethodcombined
withastaticvariable
Examineyourperformanceandresourceconstraintsand
carefullychooseanappropriateSingleton
implementationformultithreadedapplications.