Wassup reader. If the title dragged you inside this post; sorry to break you heart. I am not going to explain what is Singleton Pattern, how and why do we use it. Yet I can refer you a good read links as below { yeh .. its free .. knowledge should be free πŸ˜‰ }

  1. Wikipedia: Singleton Pattern
  2. Tutorialspoint: Singleton Pattern

Still not sure what is the best way to get the singleton behavior out of you object. I am going to demonstrate you a way to achieve Singleton Pattern using Enum.

Please run the below code in your favorite IDE ( mine is Eclipse though).

Singleton.java

public enum Singleton {
INSTANCE;

private String name;

public void setName(String name) {
this.name = name;
}

public String getName() {
return this.name;
}
}

SingletonTest.java

public class SingletonTest {

public static void main(String[] args) {
Singleton firstObj = Singleton.INSTANCE;
firstObj.setName("#coder");

System.out.println("First instance: " + firstObj.getName());

Singleton secondObj = Singleton.INSTANCE;
secondObj.setName("#moon");

System.out.println("Second instance: " + secondObj.getName());
System.out.println("First instance: " + firstObj.getName());
}

}

Output:

First instance: #coder
Second instance: #moon
First instance: #moon

As you can see we get only one instance of Singletion enum, no matter how many we create multiple instance of it. So we achieved the Singleton nature using enum.

Butttttt …Β  why enum? Isn’t there any other apporach??

Of course there are many but to know why Singleton Pattern is best achieved with Enum please read the following posts carefully and slowly πŸ˜‰

In short, by using Enum Singleton Pattern we can get Serialized and Lazy Loaded Singleton Object.

Did I forgot to mention enjoy ? πŸ˜‰

 

 

Advertisements