Singleton Design Pattern :-
it Limits no of object creation of that class is only one. Only one instance of the class we can create in the whole application.
1. Make a public class.
2. Declare variable of private and static type that will object of the class.
3. Create a private constructor .
4. Make a public static method which well return instance of the class.
Example are follows:-
public class SingletonClass {
private static SingletonClass singletonClass = null;
private SingletonClass() {
}
public static synchronized SingletonClass getInstance() {
if (singletonClass == null) {
singletonClass = new SingletonClass();
}
return singletonClass;
}
}
Example: To test that object is created only one below we can test
SingletonClass a=SingletonClass.getInstance();
SingletonClass b=SingletonClass.getInstance();
SingletonClass c=SingletonClass.getInstance();
System.out.println(a.hashCode());
System.out.println(b.hashCode());
System.out.println(c.hashCode());Output:-1791741888 1791741888 1791741888
No comments:
Post a Comment