Singleton - DP
Singleton - DP
Singleton class is a class that controls the object creation. It means the singleton
class allows us to create a single object of the class, at a time. It is usually used to
control access to resources, such as database connections or sockets. It ensures
that only one connection is made and a thread can access the connection at a time.
Nevertheless, if we try to create the second object of the singleton class, it points
to the first instance of the singleton class.
1. Break by cloning :
java.lang.Cloneable interface then invoking clone() method on its single instance
creates a duplicate object.
2. Deserialization : When a class is deserialized, a fresh instance of the class is
created and its instance variables are then set to the values which were serialized.
3. Reflection API :using java reflection api, we can tweak into a class by getting details
like its fields, constructor, invoking its methods etc. Reflection can also be used to
create new instance of a class. Obviously, if the class is Singleton, then creating a
new instance again breaks its Singleton nature.
private Singleton()
{
str = "it is an example of singleton class.";
}
//static method to create an instance of the Singleton class
// we can also create a method with the same name as the class name
public static Singleton getInstance()
{
//lazy initialization
if (s== null)
s = new SingletonClassExample();
return s;
}
}