In: Computer Science
Can you give a java code example of using a singleton pattern and factory pattern design together?
class SingletonFactory {
// static reference variable
static SingletonFactory singletonFactory;
//private consutrctor to avoid the creation of objects
private SingletonFactory() {
}
// factory method to return the object
public static SingletonFactory getInstance() {
//creating the object only once for
the first time
if (singletonFactory == null)
singletonFactory
= new SingletonFactory();
return singletonFactory;
}
}
public class TestSingletonFactory {
public static void main(String[] args) {
SingletonFactory s1 =
SingletonFactory.getInstance();
System.out.println(s1);
SingletonFactory s2 =
SingletonFactory.getInstance();
System.out.println(s2);
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me