Episode 1: Design pattern series — Singleton

I recently talked to one of my friend who currently working @Coccoc, a Vietnamese giant in browser and searching technologies about his company coding style and coding quality. One big point I learned from this talk is about coding pattern, so that I dicided to write a series of posts about this topic, to remind me about it and share it to you guys.

First post will mostly focus on the basic and very simple pattern called Singleton

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the memory of the compilers like JVM. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool

I’m going to listed here a few style of Singleton that implemented in Java programing language.

Eager initialization

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it

package com.journaldev.singleton; 
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}

}

}

}