Java Singleton Pattern
In this section, you will learn about singleton pattern in Java.
What is Singleton Pattern ?
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.
How to implement ?
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(); } }