Java — Singleton Design Pattern Example | Code Factory

  1. Declare a private constructor to prevent others from instantiating the class.
  2. Create the instance of the class either during class loading in a static field/block, or on-demand in a static method that first checks whether the instance exists or not and creates a new one only if it doesn’t exist.
package com.example.java.programming.singleton;/**
* @author code.factory
*
*/
public class EagerSingleton {
/* private constructor to prevent others from instantiating this class */
private EagerSingleton() {

}
/* Create an instance of the class at the time of class loading */
private static final EagerSingleton instance = new EagerSingleton();
/* Provide a global point of access to the instance */
public static EagerSingleton getInstance() {
return instance;
}
}
package com.example.java.programming.singleton;/**
* @author code.factory
*
*/
public class EagerStaticBlockSingleton {
private static final EagerStaticBlockSingleton instance; /* Don't let anyone else instantiate this class */
private EagerStaticBlockSingleton() {

}
/* Create the one-and-only instance in a static block */
static {
try {
instance = new EagerStaticBlockSingleton();
} catch (Exception ex) {
throw ex;
}
}
/** Provide a public method to get the instance that we created */
public static EagerStaticBlockSingleton getInstance() {
return instance;
}
}
package com.example.java.programming.singleton;/**
* @author code.factory
*
*/
public class LazySingleton {
private static LazySingleton instance; /* Don't let anyone else instantiate this class */
private LazySingleton() {

}
/* Lazily create the instance when it is accessed for the first time */
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
package com.example.java.programming.singleton;/**
* @author code.factory
*
*/
public class LazyDoubleCheckedLockingSingleton {

private static volatile LazyDoubleCheckedLockingSingleton instance;
/* private constructor to prevent others from instantiating this class */
private LazyDoubleCheckedLockingSingleton() {

}
/* Lazily initialize the singleton in a synchronized block */
public static LazyDoubleCheckedLockingSingleton getInstance() {
if (instance == null) {
synchronized (LazyDoubleCheckedLockingSingleton.class) {
// double-check
if (instance == null) {
instance = new LazyDoubleCheckedLockingSingleton();
}
}
}
return instance;
}
}
package com.example.java.programming.singleton;/**
* @author code.factory
*
*/
public class LazyInnerClassSingleton {
/* private constructor to prevent others from instantiating this class */
private LazyInnerClassSingleton() {

}
/**
* This inner class is loaded only after getInstance() is called for the first
* time.
*/
private static class SingletonHelper {
private static final LazyInnerClassSingleton INSTANCE = new LazyInnerClassSingleton();
}
public static LazyInnerClassSingleton getInstance() {
return SingletonHelper.INSTANCE;
}
}
package com.example.java.programming.singleton;import java.util.Arrays;/**
* An Enum value is initialized only once at the time of class loading. It is
* singleton by design and is also thread-safe.
*/
enum EnumSingleton {
WEEKDAY("Monday", "Tuesday", "Wednesday", "Thursday", "Friday"),
WEEKEND("Saturday", "Sunday");
private String[] days; EnumSingleton(String... days) {
System.out.println("Initializing enum with " + Arrays.toString(days));
this.days = days;
}
public String[] getDays() {
return this.days;
}
@Override
public String toString() {
return "EnumSingleton{" + "days=" + Arrays.toString(days) + '}';
}
}
public class EnumSingletonExample {
public static void main(String[] args) {
System.out.println(EnumSingleton.WEEKDAY);
System.out.println(EnumSingleton.WEEKEND);
}
}
Initializing enum with [Monday, Tuesday, Wednesday, Thursday, Friday]
Initializing enum with [Saturday, Sunday]
EnumSingleton{days=[Monday, Tuesday, Wednesday, Thursday, Friday]}
EnumSingleton{days=[Saturday, Sunday]}
package com.example.java.programming.singleton;import java.lang.reflect.Constructor;/**
* @author code.factory
*
*/
public class SingletonAndReflection {
public static void main(String[] args) {
MySingleton singletonInstance = MySingleton.getInstance();
MySingleton reflectionInstance = null;
try {
Constructor[] constructors = MySingleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
constructor.setAccessible(true);
reflectionInstance = (MySingleton) constructor.newInstance();
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
System.out.println("singletonInstance hashCode: " + singletonInstance.hashCode());
System.out.println("reflectionInstance hashCode: " + reflectionInstance.hashCode());
}
}class MySingleton {
private static final MySingleton instance = new MySingleton();
private MySingleton() {
}
public static MySingleton getInstance() {
return instance;
}
}
singletonInstance hashCode: 366712642
reflectionInstance hashCode: 1829164700
class MySingleton {
private static final MySingleton instance = new MySingleton();
private MySingleton() {
// protect against instantiation via reflection
if(instance != null) {
throw new IllegalStateException("Singleton already initialized");
}
}
public static MySingleton getInstance() {
return instance;
}
}
package com.example.java.programming.singleton;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* @author code.factory
*
*/
public class SingletonAndSerialization {

public static void main(String[] args) {
SerializableSingleton instance1 = SerializableSingleton.getInstance();
try {
// Serialize singleton object to a file.
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("singleton.ser"));
out.writeObject(instance1);
out.close();
// Deserialize singleton object from the file
ObjectInput in = new ObjectInputStream(new FileInputStream("singleton.ser"));
SerializableSingleton instance2 = (SerializableSingleton) in.readObject();
in.close();
System.out.println("instance1 hashCode: " + instance1.hashCode());
System.out.println("instance2 hashCode: " + instance2.hashCode());
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}

}
class SerializableSingleton implements Serializable {

private static final long serialVersionUID = 1L;
private static SerializableSingleton instance; private SerializableSingleton() {

}
public static synchronized SerializableSingleton getInstance() {
if (instance == null) {
instance = new SerializableSingleton();
}
return instance;
}
}
instance1 hashCode: 865113938
instance2 hashCode: 1283928880
package com.example.java.programming.singleton;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* @author code.factory
*
*/
public class SingletonAndSerialization {

public static void main(String[] args) {
SerializableSingleton instance1 = SerializableSingleton.getInstance();
try {
// Serialize singleton object to a file.
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("singleton.ser"));
out.writeObject(instance1);
out.close();
// Deserialize singleton object from the file
ObjectInput in = new ObjectInputStream(new FileInputStream("singleton.ser"));
SerializableSingleton instance2 = (SerializableSingleton) in.readObject();
in.close();
System.out.println("instance1 hashCode: " + instance1.hashCode());
System.out.println("instance2 hashCode: " + instance2.hashCode());
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}

}
class SerializableSingleton implements Serializable {

private static final long serialVersionUID = 1L;
private static SerializableSingleton instance; private SerializableSingleton() {

}
public static synchronized SerializableSingleton getInstance() {
if (instance == null) {
instance = new SerializableSingleton();
}
return instance;
}
// implement readResolve method to return the existing instance
protected Object readResolve() {
return instance;
}
}
instance1 hashCode: 865113938
instance2 hashCode: 865113938

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Password-based Door lock System

An Ultimate Step by Step Guide to Hire top Flutter app development company from India

TRON SR RANKING May 22, 2018

Securely log to blob storage using NLog with connection string in key vault.

Building digital divides through the provision of digital literacy skills — Via Wikonnect.

Composition operation on crisp and fuzzy relations

The Most Important Developer Skill Isn’t Coding

Wireless Build & Debug with Android on Xamarin is officially here!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Fundamentals of Java

Share several methods of deduplicating lists through Stream in Java 8

Cloud Storage, Java

Set in Java