In this section, you will learn about singleton pattern in Java.
In Java, singleton pattern is implemented to limit the instantiation of a class to one object. Similar to static field, instance of a class will occur only once per application.
You can implement the singleton pattern as given below :
SingletonDemo.java
public class SingletonDemo {
// Private constructor restrict from instantiating
private static SingletonDemo instance = new SingletonDemo();
private SingletonDemo() {
}
public static SingletonDemo getInstance() {
return instance;
}
// This methods is protected due to singleton
protected static void sampleMethod() {
System.out.println("Singleton Sample Method");
}
}
For implementing "singleton pattern", you need a private constructor( SingletonDemo() ) and a field to conatin its result(instance), and a static access method having name like getInstance().
SingletonExample.java
public class SingletonExample {
public static void main(String args[]){
SingletonDemo.sampleMethod();
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Java Singleton Pattern
Post your Comment