We must have heard multiple times that enums are always the best choice for implementing singleton design pattern in java. Are they really the best? If it is then how is it better than other available techniques? Let’s find out.
Writing a singleton implementation is always tricky. I already discussed a couple of methods (including my favorite method as well) in this blog post. I have written there clearly that enums provide implicit support for thread safety and only one instance is guaranteed. This is also a good way to have a singleton with minimum effort.
1. Problems with Enum as a Singleton
Having said that, like with any other thing in the universe, this approach does have its disadvantages which we will need to consider before making any decision.
- By default, enums do not support lazy loading.
- Though it is very rare but if we changed our mind and want to convert the singleton to multi-ton, an enum would not allow this.
If both above cases are no problem for anybody, the enum is probably the best choice.
Anyways, on a side note, after compilation, java enums are converted to classes only with additional methods e.g. values()
and valueOf()
… etc.
2. Enum based Singleton Example
Once we have decided to write enum-based singleton, writing it is really easy:
public enum PathUtils {
INSTANCE;
public static PathUtils getInstance() {
return INSTANCE;
}
PathUtils() {
rootPath = Paths.get("");
}
private final Path rootPath;
public Path getRootPath() {
return rootPath;
}
}
Now we use can use the PathUtils as follows:
PathUtils pathUtils = PathUtils.getInstance();
Remember that since this is an enum we can always access this via PathUtils.INSTANCE as well.
PathUtils pathUtils = PathUtils.INSTANCE
Happy Learning !!
Comments