Background
I have a situation in which I'm developing a program that runs like a thread. Basically, there is a "master" program that runs instances of sub-programs simultaneously.
Due to the nature of this system, the "sub-programs" all run under a single Java Virtual Machine. The most serious implication here is that they share memory spaces.
In my sub-program, I want to create a Logger class so that all the classes within my sub-program can log to a single location. Since this project can include many classes, I want to avoid Dependency Injection and use a Singleton.
But if I use a Singleton, the instance will be stored statically. So if the JVM has 2 instances of my program running, the Logger class will give them the same instance (because they share that memory).
I want each sub-program to have their own logger, without dependency injection.
There exists a unique identifier that I can call for each program to differentiate between them.
My Current Solution
Assume "uniqueID" is an API call that the Master Program receives and then returns what Sub-Program called it. Assume this call produces extremely little computational overhead.
public class Logger {
private static HashMap<string,Logger> instances = new Hashmap<>();
public static Logger instance() {
if(instances.containsKey(uniqueId)) {
return instances.get(uniqueId);
} else {
Logger newLogger = new Logger();
instances.put(uniqueId, newLogger);
return newLogger;
}
}
private Logger(){}
}
This solution allows each sub-program to treat the Logger class like a Singleton, but it's not quite a Singleton. It acts as an Instance Manager, that creates and returns instances based on which sub-program is interacting with the method.
My Question(s)
This solution is not technically a Singleton, but each project using it treats it like a singleton. What design pattern is it?
Also, is this the correct approach to my problem? How can I improve it?