Monday, December 11, 2017

Singleton Pattern

Definition -

    The singleton pattern means you allow only one single instance of a class in the system. There are two types of singleton pattern one is early and lazy.
    The early method would instantiate the object at the first call but will ensure that new instances cannot be created.
    The lazy method would delay the creation of the instance.

Scenario -

    The singleton pattern are best used in case of database connection, where in you need to have only instance of the connection open.
   
First we will see early method

package SingletonPattern;

public class earlymethod {
    
    public static earlymethod em=new earlymethod();
    
    public static earlymethod getearlymethod() {
        return em;
    }

}


Now we will see Lazy method

package SingletonPattern;

public class Lazymethod {
    
    public static Lazymethod lm;
    
    public static Lazymethod getlm() {
        
        if(lm==null) {
            return lm=new Lazymethod();
        }
        else {
            return lm;
        }
        
    }

}


However if we use thread then we need to be more careful. The below code will show the way to handle the pattern in a multithreaded environment.

package SingletonPattern;

public class threadsafe {

    public static threadsafe ts;
    
    public synchronized static threadsafe getts() {
        if(ts==null) {
            return ts=new threadsafe();
        }else {
            return ts;
        }
    }

}



Place to use -
1) When you need a to search for an element without the need to access the representations.





No comments:

Post a Comment