mercredi 19 septembre 2018

Shared subservient object

I have a template class Foo that has a method, barMethod, that requires a Bar object. I could have each individual Foo object create Bar objects as needed, but I don't want to do that because it will be slow, and there is a good chance that different Foo objects could use the same Bar object.

Given that, I would like to have a BarManager object that has the existing set of Bar objects. The Foo objects could then ask it for Bar objects, and if an appropriate one already exists, the manager would simply return it. If it doesn't the manager would create a new one and return it.

It seems to me that there are two problems with implementing the "manager" approach.

  1. The manager would have to be a global variable, which I would prefer not to do.
  2. BarManager and Bar are both template classes, so even if I were to make the manager a global variable/object, I'm not sure how that would work. I guess I could make the global variable a void * and cast it whenever it is de-referenced to the appropriate templated class, but that seems really ugly.

There has to be a way to do this that isn't so ugly (perhaps using an auto pointer?). What is it?

Aucun commentaire:

Enregistrer un commentaire