Reputation: 49
I have one class whose single instance needs to be used by multiple classes in Java. I found two solutions for the same: 1. Pass the instance as method parameters 2. Use Static factory
My question is if I used static factory, how can I differentiate the incoming requests when I am using the static method. I want to avoid the 1st solution as there are many classes that are going to use this instance. Also, recommend the best design if other than mentioned above.
Code Example:
class MyClass{
Map<String, List<String>> myMap=new ConcurrentHashMap();
public static void addToMap(String key, String value){
if(myMap.containsKey(key)){
List<String> stringList=myMap.get(key);
stringList.add(value);
}
else{
myMap.put(key,value);
}
}
}
I want to perform this add method at many places while program execution for eg:
Method addEmployee():
if(employeeName==null){
MyClass.addToMap("ER101", "Name Error");
}
Method insertInDB():
catch(SQLException e){
MyClass.addToMap("SQL", "Error Occurred in DB Operation");
}
Thanks
Upvotes: 0
Views: 1094
Reputation: 239
The best design would be to make your class as Singleton class. For your usage i think you can follow the below steps,
then, have a static function inside that class to return the instantiated object of your class.
you can have your own if(classobj==nul) check to verify if its already instantiated or not(only on first call it will be null , further calls it wont be null) and return the object.
Cheers :)
Upvotes: 0
Reputation: 1840
There are a number of ways to make the same instance of a class available to different callers such as threads or requests.
One of the easiest things you can do is create a singleton as shown above. The problem with singletons is that there can only ever be one of them, as they are generally set up to enforce that there is a single instance of them.
Better is to create your instance, and pass it to the things that need it. If you're creating a web application or similar, you can use a Dependency Injection framework such as SpringFramework to achieve this.
Injecting your instance where it is needed will mean it will be easier to replace this instance with a dummy instance for testing, and during testing you'll be able to create many instances of this class configured in different ways to test.
Upvotes: 2
Reputation: 1234
As 12dollar says: Use the Singleton Design Pattern, and ask for that instance to the Singleton Class:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Then you could call getInstance()
.
Upvotes: 0