In this example, a reference to the instance of the singleton object is obtained by the following:
MySingletonEnum mse = MySingletonEnum.INSTANCE;
Once you have the singleton's reference, you can call any of its methods like so:
Several years ago, a close friend of mine who owned a small software company
asked my help to interview a candidate. Because I always i nd software job
interviews great engineer‐to‐engineer experience, I didn't hesitate to jump at the
opportunity. The candidate had only a few years of job experience but graduated
from a good university and was dei nitely sharp. We had a long chat about Java,
JPA, Spring, and other well‐known Java frameworks. He was eager to learn and try
new stuff and handled all questions calmly.
After about an hour, the interview was i nished, but we continued to talk
casually. I asked him about the topics he had recently read, and his reply was
Head First Design Patterns . I inquired about which pattern he found most
interesting or simply wanted to talk about. Not surprisingly, it was the singleton
pattern. This made my spider senses tingle. The candidate thought the singleton
pattern was simple and easy to implement, so it would be a safe topic. The truth
was, it wasn't. If he had chosen another pattern such as the decorator, I would not
have had the opportunity to dive into the more advanced topics of this seemingly
I then asked the candidate how he would implement a singleton. He responded
with the classic private constructor method, which clearly showed he hadn't read
Effective Java and had no clue about the enum type singleton. Later I asked, “What
if I used rel ection to change the access level of the constructor back to public?”
He was surprised, but I could clearly see from his eyes that he was more interested
in going back home and trying this out. He couldn't come up with a solution, but
he also didn't make up a nonsense response. He was busier digesting and thinking
about the rel ection idea.
This job candidate may have missed the right answer, but he showed he was
passionate and eager to learn. He was hired and became one of the best developers
I have ever worked with.
IMPLEMENTING THE SINGLETON PATTERN IN JAVA EE
All the code examples so far have demonstrated the use of singletons within the context of Java SE.
Although you can use them in Java EE, there is a more elegant and easy‐to‐use approach: singleton