For a singleton class it allows to create only one object of the class
package singelton;
/***
* Steps to create a Singleton class Create a standard java class Create an
* instance of the same class like private static SingleTone instance = new SingleTone();
* create a private default constructor
* create a method and return the instance
*
* @author sudas
*
*/
public class SingleTone {
public static void main(String[] args) {
SingleTone obj1 = SingleTone.singleInstance();
SingleTone obj2 = SingleTone.singleInstance();
System.out.println(obj1);
System.out.println(obj2);
}
private static SingleTone instance = new SingleTone();
private SingleTone() {
// TODO Auto-generated constructor stub
}
public static SingleTone singleInstance() {
return instance;
}
}
When you run this you will see both the objects (obj1 and obj2) are pointing to the same memory on hip, so basically obj1 and obj2 both are same objects of class Singleton
singelton.SingleTone@2a139a55
singelton.SingleTone@2a139a55
No comments:
Post a Comment