Singleton design pattern



Singleton pattern is a design solution where an application wants to have one and only one instance of any class.It saves memory because object is not created with each request. Only single instance is reused again and again.
But how to make any class singleton is not so easy task, because there are several way in which singleton can break.
Steps:
1.      Make constructor private, so not directly instantiated class
2.      Make a static method which produce existing instance if one available else new
3.      Override clone() method. One cannot create a cloned object which also violates singleton pattern.
4.      If Singleton is class is serializable then once it serialized again deserialized it, but it will not return singleton object.

Example:
public class MyUser implements Cloneable{

    private String name = null;
    private static MyUser user = null;

    private MyUser() {
    }

    public static MyUser getInstance() {
        if (user == null) {
            user = new MyUser();
        }                                               
        return user;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return null;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Now, make modification in above example- if Serializable, you need to override readResolve() method that violate singleton.

public class MyUser implements Cloneable, Serializable{

    private String name = null;
    private static MyUser user = null;

    private MyUser() {
    }

    public static MyUser getInstance() {
        if (user == null) {
            user = new MyUser();
        }
        return user;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return null;
    }
    protected Object readResolve(){
        return getInstance();
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
In multithreading environment may be a problem?

Suppose there are two threads T1 and T2. Both comes to create instance and execute “user==null”, now both threads have identified instance variable to null thus assume they must create an instance.
So, why not make getInstance() method Synchronized.

public synchronized static MyUser getInstance() {
        if (user == null) {
            user = new MyUser();
        }
        return user;
    }

“Instance of Singleton class can be created per classloader, If singleton class loaded by two classloaded then two instance are created.”

No comments:

Post a Comment