Singleton Class
Suppose , we have the same requirement or the same uses of a class method or other so we can use a singleton class. in the singleton class, you can create only one object. and reuse of this object. so this purpose of the singleton class.
If Several people have the same requirement then it's not recommended to create separate an object for the requirement.
we have created only one object and we can reuse the same object for every similar requirement so that performance and memory utilization will be improved. this is the central idea of singleton classes.
Private Constructor
The use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time. We will see in the below example how to use the private constructor for limiting the number of objects for a singleton class.
Application of Singleton Class is like Runtime. runtime is the best example of the singleton class.
The example of Singleton Class withing the use of the private constructor.
class SingletonPrivateClass{
private static SingletonPrivateClass obj= null;
private SingletonPrivateClass(){
//Private Consturucor
}
public static SingletonPrivateClass CreateobjecMethod(){
//if the already object is created so condition is false and direct to display mesg,
if(obj == null){
obj = new SingletonPrivateClass();
}
return obj;
}
public void display(){
System.out.println("SingletonClass Example.");
}
}
public class PrivateConstructor {
public static void main(String[] args) {
//Create Singleton class object ..........
SingletonPrivateClass obj = SingletonPrivateClass.CreateobjecMethod();
obj.display();
}
}
This code misses major things if you consider multithreading
ReplyDeleteits just an example ... to understand Singleton or private constructor Nothing els...
ReplyDelete