Singleton Design Pattern
When?
- Sometimes it's appropriate to have exactly one instance of a class and provide a global point of access to it.
- EX:Lets Assume that there is a product store and It would like to maintain the products of their store in a List.We dont know how many stores access this list and update the list details.In this case,if we create multiple instances if store A update one instance,Store B doest not know the new list if it access another instance of this class.So to avoid this,we will create only one instance and allow all the stores access the same one instance.
- Note:In this Pattern only one instance is created in entire JVM for this class.If we have in distributed system ,for every JVM container there will be one instance.If we have two JVMs in our machine, we have 2 instances per each JVM.
How??
step1: Create a class and restrict the class as no body can access the class.To do this Mark the constructor as Private.
public class SingletonDemo {
private
SingletonDemo () {}
}
step2:As we mark the constructor as private ,No other class create a instance of this class.So We need to create a instance of this class and write a method to return the instance.Mark this method as static.so that other classes can access this method.
public class SingletonDemo {
private static SingletonDemo instance = null;
private
SingletonDemo () {}
public static SingletonDemo getInstance() {if (instance == null) { instance = new SingletonDemo(); } return instance; } }
Done....
Note:This simple singleton pattern is not working in multithread environment.Assume that two thread are actually call this method at a time it will call the if block and create two instances (prob)
Solution:Mark themethod as synchronized
No comments:
Post a Comment
test