Singleton Design Pattern Example Program
Singleton Design pattern will allow only one object per Class(JVM).
Before Writing Singleton Design pattern you should follow these steps.
#1). create an instance as static and return type as The same class, and it should be assigned as null.
#2). "Create a Constructor as private" to deny the creation of object from other class.
#3). Write a static method to create object for our class.It should be Once for a class.
#4). At last return the class Object.
Here We are creating the object once only not again and again.The first time created object is returning again when you called.
Before Writing Singleton Design pattern you should follow these steps.
#1). create an instance as static and return type as The same class, and it should be assigned as null.
private static Singletonn instance = null;
#2). "Create a Constructor as private" to deny the creation of object from other class.
private Singletonn(){ }
#3). Write a static method to create object for our class.It should be Once for a class.
public static Singletonn getInstance(){ }
#4). At last return the class Object.
Here We are creating the object once only not again and again.The first time created object is returning again when you called.
package javabynataraj.basic; class Singletonn { private static Singletonn instance = null; private Singletonn(){ } public static Singletonn getInstance(){ if(instance==null){ instance = new Singletonn(); } return instance; } } public class Singleton{ public static void main(String[] args) { System.out.println("before calling ..."); System.out.println(Singletonn.getInstance()); System.out.println("Once Called"); System.out.println(Singletonn.getInstance()); System.out.println("Second time called"); } }Reference books:
Design Patterns : Elements of Reusable Object
DESIGN PATTERNS IN JAVA 2nd Edition
Data Structures And Algorithms With Object-oriented Design Patterns In Java 1st Edition
Dependency Injection: Design Patterns Using Spring and Guice