A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://howtodoinjava.com/java/enum/is-enum-really-best-for-singletons/ below:

Are Java Enums Really the Best Singletons?

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.

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 !!


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4