When you define a class, it means you can create a large number of its object at runtime. It is because of
public
constructor.
class Box {
public Box()
{
}
...
...
...
}
Box b1 = new Box();
Box b2 = new Box();
..
Box b100 = new Box();
but if you apply singleton pattern. it means you can create ONLY ONE object with it. In this pattern constructor is
private
it means you can't use like
Box b1 = new Box();
Box b2 = new Box();
So singleton pattern is "Defining a Class with private constructor so that the code which is outside the class cannot create it".
following code creates a singleton class.
class Box{
private static Box instance ;
private Box()
{ ...
}
public static Box getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}
public void doSomething()
{ ...
}
}
With the above defination you can access the object of class Box by
Box b = Box.getInstance();
b.doSomething();
But it is important to understand that where do we use singleton and we we not.
If we want a single gateway to common set of functionalities we use singleton class. like Logging, Configuration of Application, Server Client achitecture, Resource access, Global/shared values/variables ( company email, address etc.). common Data store acess point. If wisely used it saves lots of memory and increase performance.
How to determine the singleton behaviour of a Class.
In the simplest form,
If a entity in your application co-exists with different property values then it is not a candidate for singleton. for e.g. In school System , "Student" : Student-1 , Student-2 has a common property / behaviour but property values are different. (their name,age,address class are different).
If a Entity exists in System that is common and its property values are same,its a candidate for Singleton class. for e.g. Playground, Auditorium, School Notice Board. these are single instance object throughout the School system.
A in-depth analysis is required to get a list of classes that we can make singleton.
please refer
http://www.oodesign.com/singleton-pattern.html[
^] for more detail