Singleton Pattern Design Revisited

Singleton Pattern Using Enum in Java

What is a singleton and how to implement it

Daniele Quero, PhD
Published in
3 min readJun 27, 2022

--

Singleton is a design pattern used to create a unique instance of a class: through the runtime, there will be only one.

The classic implementation of this pattern uses a combination of static methods to check if there already is an instance (and returns that) or, otherwise, creates a new one:

public final class User{      

private static User INSTANCE;

private User() {}

public static User getInstance() {
if(INSTANCE == null)
INSTANCE = new User();

return INSTANCE;
}
// getters, setters, other methods
}

Inside the class, there is a static field, the instance of the class itself, a private constructor (not accessible from outside) and a static getInstance() method: it checks if the instance is null (and then creates and returns it) or returns the current one.

These methods are accessed through the class itself (static) and don’t allow direct instantiation since always the same instance is returned: you can not instantiate it by yourself or set it to null or whatever.

But hey! Java users…

--

--

Daniele Quero, PhD
Geek Culture

A professional developer with passion for game developing and skill-growing. A former Nuclear Physics Researcher who changed his life to pursue his dreams