Head First Design Patterns Series / 5 (One of a Kind Objects: The Singleton Pattern)

Building Extensible & Maintainable Object Oriented Software

Merve Arslan
Odeal-Tech
2 min readMar 16, 2023

--

The singleton design patterns allow only one instance of the class to be taken. In this way, creating and copying a new one from the object is prevented and it makes the related object global. Also, when that object is needed, the previous instance of the object is called. In general, a singular structure is used when it is desired to control how many objects are produced from a class.

The government is an excellent example of the Singleton pattern. A country can have only one official government. Regardless of the personal identities of the individuals who form governments, the title, “The Government of X”, is a global point of access that identifies the group of people in charge.

If your class is self-contained and not dependent on complex initialization, creating a class where all methods and variables are defined as static would be the same as a singleton.However, because of the way static initializations are handled in Java, this can get very messy, especially if multiple classes are involved. Often this scenario can result in subtle, hard-to-find bugs involving order of initialization. Unless there is a compelling need to implement your “singleton” this way, it’s far better to stay in the object world.

In Java, global variables are basically static references to objects. There are a couple of disadvantages to using global variables in this manner. We need to keep in mind the intent of the pattern: to ensure only one instance of a class exists and to provide global access. A global variable can provide the latter, but not the former. Global variables also tend to encourage developers to pollute the namespace with lots of global references to small objects. Singletons don’t encourage this in the same way, but can be abused nonetheless.

We can also use singleton pattern using enum. Like that ↴

public enum Singleton {
UNIQUE_INSTANCE;
// more useful fields here
}
public class SingletonClient {
public static void main(String[] args) {
Singleton singleton = Singleton.UNIQUE_INSTANCE;
// use the singleton here
}
}

You’ve now added another pattern to your toolbox. Singleton gives you another method of creating objects — in this case, unique objects.

--

--