Java - A Better Singleton Approach With Enums
In this article, we are going to see what other way we can have to achieve singleton implementation and you are propably very familiar with the concept I will talk about- in a different way.
I think you get the clue off the image above. Yes, we are going to use enums to implement singleton structure.
Firstly, let’s take a look at an ordinary singleton implementation and then see why we better off using enums for singleton implementations. The singleton you can find below simple has a private constructor and a static instance of itself. Whenever you need an object of this type, getInstance() method is called and it gives you the instance (initialize before returning if it is the first time).
public class ClassicSingleton {
private static ClassicSingleton instance;
private ClassicSingleton() {
}
public synchronized static ClassicSingleton getInstance() {
if (instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
public void operate() {
// some method
}
}
In Java, we have a special type of class called Enums and everyone playing with Java for some time has most probably heard of it before. We use them when we need to define a set of constants that cannot be changed. This is the most common use of enums but now, we are going to use them to implement famous singleton pattern.
So, why are enums suitable and good for creating singletons?
- Enums are guaranteed to be instantiated only once.
- Enums are thread-safe by nature, but inner structure such as methods of it must handle its own thread-safety.
- They are already serializable.
- Cleaner code
Let’s look at how we can implement a singleton with enum over an example. Imagine we are using TCP in our application and naturally we want to have only one instance of it as duplicate instances may lead problems such as creating two instances of TCP channel and starting them results in Binding Exception. So we do not want that and we are going to use singleton with enum.
public enum Channel {
INSTANCE;
public void open() {
// logic for opening channel
}
public void close() {
// logic for closing channel
}
public boolean isOpen() {
return true;
}
}
We have INSTANCE enum type which we are going to use to access singleton. Then, we simply define some methods according to our logic. Finally, We can use it like
Channel.INSTANCE.open();
Channel.INSTANCE.close();
Channel.INSTANCE.isOpen();
As you see, it does look cleaner than traditional singleton implementation. With its benefits, you should always consider using enum singletons before creating your own singleton.
I hope you like the article about singletons with enum and find it useful. I will keep writing about more on Java and its technologies so you can keep in touch if you want more articles like this and you can even suggest me topics to talk about.