One instance of Report per instance of Simulation: use a singleton?

点点圈 提交于 2019-12-11 13:52:44

问题


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:

  1. Making a kind of "singleton" report class that allows the creation of no more than one Report per Simulation. Is this possible?

  2. Making a SpecialSimulation class that extends Simulation, and in SpecialSimulation include a singleton that contains a Report. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!