Square CSS

Showing posts with label singleton class in java. Show all posts
Showing posts with label singleton class in java. Show all posts

Sunday, October 21, 2018

Singleton Class In Java

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 :







                       Nowadays in some office, it is required to stay on your desk and work for  ... 


    Some Algorithms

    Algorithm: Tower of Hanoi

    Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

    Popular Posts