One report instance per Simulation instance: use singleton?

I wrote code that runs many different simulations, each in its own Simulation object. To extract results from Simulation , you first need to ask Simulation to create an instance of Report (as one of the Simulation children).

Even if Simulation can contain many instances of Report , the creation process is quite expensive, so if there is already a Report in this Simulation , I want to reuse it, rather than create a new one.

Report instances access many different classes in my code. I would like to avoid repeating the code, which first checks if Report exists in this particular Simulation , and then based on this either get the existing one or create a new one.

I really want only one instance of Report per Simulation - sort of like a singleton ...

I see two ways:

  • Creating a kind of "singleton" report class that allows you to create no more than one Report per Simulation . Is it possible?

  • Creating a SpecialSimulation class that extends Simulation , and in SpecialSimulation includes a singleton containing Report . Is this too much?

Simulation and Report are the commercial Java APIs for which we have a license; I can not change their source code.

Doing your best to learn the ropes of Java and OOP ...

+1
source share
1 answer

If I understand your question correctly, you really 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 is very simple, but on the negative side, it can theoretically lead to the fact that the report is created several times in a multi-threaded environment, but this would be a rare case, and you are guaranteed that at least all the streams are the same report

+2
source

All Articles