Open main menu

CDOT Wiki β

Changes

OpenOffice temporary template

2,571 bytes added, 17:44, 20 June 2010
Singletons
====Singletons====
In Singleton Pattern, the class can only create a single instance. We want a class to have only a single instance for various reasons.
 
Sometimes, we want use a global object to keep information about your program. This object should not have any copies. This information might be things like configuration of the program, or a master object that manages pools of resources. So when you need a resource, you ask the master object to get it for you. Now if there were many copies of this master object, you would not know whom to ask for that resource. This single object should not be allowed to have copies. Singleton Pattern forces this rule so that programmer doesn't have to remember about not creating copies. Singleton pattern will create an instance if it doesn't exist and will not create any new instance if an instance already exist. It will just return a reference to that single instance.
 
<pre>
 
class ProgramConfiguration{
 
public ProgramConfiguraiton(){
 
//default constructor code
 
}
 
}
 
</pre>
 
A new instance of a class is created by the constructor. Most of the time, we have a public constructor, which is called to create a new instance. Since we want to prohibit multiple instance, we have to restrict access to the constructor. This is done by making the constructor private.
 
<pre>
 
class ProgramConfiguration{
 
private ProgramConfiguration(){
 
//default private constructor code
 
}
 
}
 
</pre>
 
then we create a static public method that will make sure that only one instance lives in the whole program.
 
<pre>
 
class ProgramConfiguration{
 
private static ProgramConfiguration _configObject;
 
private ProgramConfiguration(){
 
//default private constructor code
 
}
 
public getInstance(){
 
/*
 
if an instance exist return that instance otherwise
 
call the constructor to create an instance and return it.
 
*/
 
if(_configObject == null){
 
_configObject = ProgramConfiguration();
 
}
 
return _configObject;
 
}
 
}
 
</pre>
 
So anytime you want to get that single object, you call the getInstance() method.
 
<pre>
 
main(){
 
/*
 
no access to default constructor. so if you did
 
ProgramConfiguration pc = new ProgramConfiguration();
 
you will get compilation error.
 
*/
 
ProgramConfiguration pc = ProgramConfiguration.getInstance();
 
ProgramConfiguration newpc = ProgramConfiguration.getInstance();
 
/*
 
in the above code pc and newpc both point to the same static object. when
 
getinstance() is called for the second time, it finds that _configObject is not null
 
anymore, so it doesn't call the constructor to create any new instance.
 
*/
 
}
 
</pre>
====...====
1
edit