SingleTon in Java
Singleton is a design pattern that ensures that a class can only have one object.
Define a class that has only one instance and provides a global point of access to it.
Static member: It gets memory only once because of static, it contains the instance of the Singleton class.
Private constructor: It will prevent instantiating the Singleton class from outside the class.
Static factory method: This provides the global point of access to the Singleton object and returns the instance to the caller.
Its used in
Logging,
Caching,
thread pools,
configuration settings
etc..
- Advantages:
- Saves memory because the object is not created at each request. An only a single instance is reused again and again.
Thread Safe
class Playground {
public static void main(String[ ] args) {
SingleTon singleTonClass = SingleTon.getInstance();
System.out.println("Hello Java");
}
}
class SingleTonClass{
private SingleTonClass(){}
private static volatile SingleTonClass instance = null;
public static SingleTonClass getInstance(){
if(instance == null)
{
synchronized(SingleTonClass.class)
{
if(instance == null)
{
instance = new SingleTonClass();
}
}
}
return instance;
}
}
class SingleTon{
private void SingleTon(){};
private static class SingleInstantce{
private static final SingleTon instance = new SingleTon();
}
public static SingleTon getInstance(){
return SingleInstantce.instance;
}
}
Not Thread Safe
class Playground {
public static void main(String[ ] args) {
SingleTonClass singleTonClass = SingleTonClass.getInstance();
System.out.println("Hello Java");
}
}
class SingleTonClass{
private SingleTonClass(){}
private static SingleTonClass instance = null;
public static SingleTonClass getInstance(){
if(instance == null)
{
instance = new SingleTonClass();
}
return instance;
}
}
Comments
Post a Comment