Question

I have a class (class A) which there exist many instances of at run time. This class uses another class (class R) which handles resource allocation. Due to the fact this second class (class R) is doing resource allocation for all instances of class A there must only be a single copy of it.

So it looks like this:

Class P (Parent) 
Class A[64], which are childs of Class P 
Each of these requires access to the single instance of Class R

I'm wondering the best solution of this.

  1. Let the parent (Class P) instantiate class R and pass the instance into each Class A. Problem: Class P doesn't care about Class R and has no use for it. It seems daft for it to have to manage it.
  2. Global variable, perhaps hidden in a namespace Problem: Anyone can then use it, and it should be restricted to Class A.
  3. Static variable inside Class A, so all instances of Class A have access to the same instance of Class R. Problem: Static class variables are evil

Or something I've not thought of?

Was it helpful?

Solution

Let class R contain an instance to itself, ie. The singleton pattern.

Then you can do:

class A
{
R *resource;
public:
A() { resource = R::getInstance(); }
}

and from then on use 'resource' as a new class pointer, just in case you change your mind how things work later on.

However, what might be better and more flexible is for the parent to grab the instance. For example, in class P:

classA = new A(R::getInstance());

This way you can easily change the resource class if needed (eg. for unit testing), but class P isn't managing the resource object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top