SINGLETON DESIGN PATTERN

Singelton design pattern is used where you want a single instance
of your class to be created through out your application,like if your
are working on any database connection application and you want
only a single connection to get created then you can use this pattern.
There are a few ways to implement this pattern.one of the
implementation way is given in above example.i think we should also
put the synchronize keyword in the method which is returning the
instance of class, to be thread safe.Other way to implement this
pattern is to make the constructor of class as private and all the
method as static.



Here is a code Snippet

public class MySingleton{
private static MySingleton s=null;
private MySingleton(){}
public static MySingleton getInstance()
{
synchronize(MySingleton.class)
{
if(s==null){s=new MySingleton();
}
}
return s;
}
}

0 comments:

Post a Comment