|
|
Title |
Creating a Singleton
|
Summary |
A singleton is a handy to share a resource or data. This is done using a class that only creates one instance of itself. |
Contributor |
John McTainsh
|
Published |
28-Oct-2000 |
Last updated |
28-Oct-2000 |
|
|
Description.
A singleton is a object that is limited to creating only one
instance of itself. This can be useful when you want need to share
some data or a resource with other parts of your application.
How to create a singleton.
The following class implements a singleton with the following steps. First, make the
constructor private. Second add a static instance of the class that is
initialised only once in the getInstance() where a reference
to the class is returned.
The variable m_dCurrentRate is only provided to
show the functionality of the class.
/////////////////////////////////////////////////////////////////////////////
//Class that only creates a single instance of itself
class TheSingleGuy
{
//Attributes
static TheSingleGuy m_TheInstance;
private double m_dCurrentRate;
//Constructor is private so can only be made internally
private TheSingleGuy()
{
m_dCurrentRate = 100.0;
}
//Accessor and creator of the singleton
static TheSingleGuy getInstance()
{
if( m_TheInstance == null )
m_TheInstance = new TheSingleGuy();
return m_TheInstance;
}
//Mutalators for the interest rate
void setRate( double dRate )
{
synchronized( this )
{
m_dCurrentRate = dRate;
}
}
double getRate()
{
synchronized( this )
{
return m_dCurrentRate;
}
}
}
To use this class do not call the constructor. Simple call
getInstance() and use this value to access the class. Note
in the example the rate is set for both instances to be the same.
Also note synchronized( this ) is used. This is not necessary
in this example but should be considered if sharing a singleton
across several threads.
TheSingleGuy sg1 = TheSingleGuy.getInstance();
TheSingleGuy sg2 = TheSingleGuy.getInstance();
sg1.setRate( 200.0 );
sg2.setRate( 300.0 );
System.out.println( "Rate 1 = " + sg1.getRate() );
System.out.println( "Rate 2 = " + sg2.getRate() );
|