Powered by Blogger.

Singleton Design Pattern Example Program

>> Tuesday, April 19, 2011

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.

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
  • Related Posts Plugin for WordPress, Blogger...
    © javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.