问题
I have written code that runs many different simulations, each in its own Simulation
object. To extract results from a Simulation
, we first have to ask Simulation
to create an instance of Report
(as one of Simulation
's children).
Even though a Simulation
can contain many instances Report
, the creation process is quite expensive, so if there already is a Report
in that particular Simulation
, I want to re-use it rather than create a new one.
The Report
instances are accessed from many different classes in my code. I'd like to avoid replicating code that first checks whether a Report
already exists in that particular Simulation
, then based on that either get the existing one or make a new one.
I really only want there to be one instance of Report
per Simulation
-- kind of like a singleton...
I see two avenues:
Making a kind of "singleton" report class that allows the creation of no more than one
Report
perSimulation
. Is this possible?Making a
SpecialSimulation
class that extendsSimulation
, and inSpecialSimulation
include a singleton that contains aReport
. Is this overkill?
Simulation
and Report
are from a commercial Java API that we have a license for; I can't modify their source code.
Doing my best to learn the ropes of Java and OOP...
回答1:
If I understand your question correctly, you really just want to do something like this:
public class ReportManager {
final static ConcurrentMap<Simulation, Report> reports = new ConcurrentHashMap<Simulation, Report>();
public static Report getReportForSimulation(final Simulation simulation){
if (!reports.containsKey(simulation)) reports.putIfAbsent(simulation, simulation.getReport());
return reports.get(simulation);
}
}
Then use the ReportManager to retrieve the Reports. On the positive side, it's very simple, but on the negative side it may theoretically result in a report being generated multiple times in a multithreaded environment, but it would be a rare occurance and you're guaranteed that at least all threads see the exact same Report
来源:https://stackoverflow.com/questions/8848027/one-instance-of-report-per-instance-of-simulation-use-a-singleton