Sponsered Links
Categories
Sponsered Links

Java SingletonPattern class.

 

This example demonstrates how to implement a SingletonPattern on a class in java. In the program below gets instances of SingletonPattern two times but the method getInstance() will return the same object without creating a new one. The code of the program is given below:

public class SingletonPattern{
  private static SingletonPattern instance;
  private SingletonPattern(){}
  public static synchronized SingletonPattern getInstance(){
     if (instance == null)
     {
        instance = new SingletonPattern();
  }
  return instance;
}
public static void main(String arg[]){
  System.out.println("The output of two instance:");
  SingletonPattern sp=new SingletonPattern();
  System.out.println("First Instance: "+sp.getInstance());
  sp=new SingletonPattern();
  System.out.println("Second Instance:"+sp.getInstance());
}

 
 
Sponsered Links
Latest Updates
 
All Content of this site is for learning only. We do not warrant the correctness of its content. The risk from using it lies entirely with the user. While using this site, you agree to have read and accepted our terms of use and privacy policy.
Copyright © 2009 JSPSERVLETTUTORIAL.INFO All Right Reserved