Java Singleton Class Example Using Private Constructor
- We can make constructor as private. So that We can not create an object outside of the class.
- This property is useful to create singleton class in java.
- Singleton pattern helps us to keep only one instance of a class at any time.
- The purpose of singleton is to control object creation by keeping private constructor.
=====> the main class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package designpattern;
/**
*
* @author jiteshupadhyay
*/
public class DesignPattern {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}
===>the singleton class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package designpattern;
/**
*
* @author jiteshupadhyay
*/
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){ }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}