1.1 What is Singleton ?
Singleton basically means one. That is you can create only one instance of that class
1.2 How to Implement a Singleton?
- The instance is stored as a private static variable(the instance is created when the variable is initialized, at some point before the static method is first called.
- Declaring all constructors of the class to be private and
- Providing a static method that returns a reference to that instance
1.3 Different Types of Implementation
Singleton design pattern can be implemented by two ways as mentioned below:
- Eager Instantiation
- Lazy Instantiation
Eager Instantiation:
- According to the principles of Eager Instantiation, the object should be created in advance and should be ready to use.
- The very first line of this Singleton class that is private static Singleton instance = new Singleton();
- Eager instantiation is thread safe.
Lazy Instantiation:
- Lazy initialization of an object means that its creation is deferred until it is first used. Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirement.
- The very first line of this Singleton class that is : private static Singleton instance = null;
- Lazy instantiation is not thread safe.
Eager Initialized Singleton Class Example
package com.coding.bee.dp.creational.singleton;
public class EagerSingletonAbc {
private static EagerSingletonAbc instance = new EagerSingletonAbc();
private EagerSingletonAbc() { }
public static EagerSingletonAbc getInstance() {
return instance;
}
}
package com.coding.bee.dp.creational.singleton;
public class EagerSingletonDriver {
public static void main(String[] args) {
EagerSingletonAbc abc1 = EagerSingletonAbc.getInstance();
EagerSingletonAbc abc2 = EagerSingletonAbc.getInstance();
System.out.println(abc1.hashCode());
System.out.println(abc2.hashCode());
}
}
Lazy Initialized Singleton Class Example
package com.coding.bee.dp.creational.singleton;
public class LazySingletonAbc {
private static LazySingletonAbc instance = null;
private LazySingletonAbc() { }
public static LazySingletonAbc getInstance() {
if (instance == null) {
instance = new LazySingletonAbc();
}
return instance;
}
}
package com.coding.bee.dp.creational.singleton;
public class LazySingletonDriver {
public static void main(String[] args) {
LazySingletonAbc abc1 = LazySingletonAbc.getInstance();
LazySingletonAbc abc2 = LazySingletonAbc.getInstance();
System.out.println(abc1.hashCode());
System.out.println(abc2.hashCode());
}
}