If we would ever speak, what a design pattern is, that answer would be that a well described solution to a common software problem.
One of them is about which we will discussing is “Singleton”. Singleton pattern lies under “Creational design pattern” group. Here is the list of this group.
Creational Design Patterns
- Singleton Pattern
- Factory Pattern
- Abstract Factory Pattern
- Builder Pattern
- Prototype Pattern
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the Java virtual machine.
Implementation
- Make constructor as private
- Write a static method that has return type of object this singleton class. The concept of Lazy Initialization is used to write this static method.
package com.denizkaradal.singleton;
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton ();
}
return instance;
}
}