- Next »
- « Previous
Learn Singleton Pattern
May you have heard "Singleton Pattern" if you learn OO in java. So at this time I will share you how to apply Singleton Pattern on our java code. Before we apply it to our code I wanna explain about Singleton Pattern. Singleton pattern is OO pattern which useful when we need to create just one instance of object per application (please remember the word single in singleton). Now, let see the example of code snippet below : public class Singleton{
in this code above we create Singleton class with have static property named, instance and we give it a value, an instance of Singleton. And the important thing you must pay attention for is we make constructor private (we hide constuctor). It useful to avoid direct instantiation of this class. Finally, we want to get an instance of this class so we create method to get instance property 's value (it just a static getter method). Now, to have an instance of Singleton class we can call the getInstance() method.
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance(){
return instance;
}
}
Singleton singleton = Singleton.getInstance();
that's short explanation of Singleton pattern. Hope will help you. On next post I will show you how to write Singleton pattern code with another style.