A singleton class is a class which has one object at a time. In other words, a class having one and only one instance at a time is known as a singleton class.
This can be achieved by following :
- Make the method which returns the object as static. In our case, the method is getInstance().
- Make the constructor as private.
- Check for the instance of the class in the static method. If the instance is not there then create the instance using new operator. Otherwise, return the instance.
Example :
class MySingleton{ private static MySingleton ms=null; public String s; // create a private constructor private MySingleton(){ s="Singleton from Play Java"; } /* create a static method to return the instance of the class. If the instance is not present then create one */ public static MySingleton getInstance(){ if(ms==null) ms=new MySingleton(); return ms; } } |
Uses Cases:
- Singleton class are mostly used where the single data is required to create on the first call and retains its instance until the closure of application.
- Used for logging, caching, configuration settings, thread pools, etc.
Refer the video tutorial :
☛ Next >> Mouse Pointer Random Movement In Java
Nowadays in some office, it is required to stay on your desk and work for ...
No comments:
Post a Comment