Given two classes:

class A {
    B* b_;
    A(B* b){
        b_ = b;

class B {}

B is a class that should be used only inside A so I would like not to expose its creation to whatever class uses A. Moreover, B should not be created every time an instance of A is needed (it has a slow initialization).

Given that I would like to reuse the same instance of B, but I do not really need to make it Singleton, could be a good idea creating a Factory which holds an internal reference to an instance of B?

Something like:

class Factory {
    B* b_;
    A* createA() {
        if(b_ == NULL)
            b_ = new B();
        return new A(b_);

My doubt is that I do not find anything useful googling for "stateful factory" and maybe I overlook some drawback in this approach.

  • Do you intend the instance of B to last forever, e.g. until the program shuts down? – rwong Mar 3 '17 at 8:54
  • Probably yes. As I said B is slow in creation so it is better to reuse the same instance, but it is not mandatory to have only one instance: multiple instances don't break application logic, they only waste resources. – Marco Stramezzi Mar 3 '17 at 9:05
  • Try stackoverflow.com/questions/26013650/… – rwong Mar 3 '17 at 9:14

In a multi-threaded environment, you may have multiple instances of B created simultaneously. Other than that, your design solves all of your requirements with the least amount of code. In general, singletons complicate multi-threading in the future.

I would not call it a factory. It is a lazily initialized reusable instance.

  • So, I should mark as static the field b_ of Factory (so I use the same instance of B at every creation of A) and protect its initialization with sinchronization logic, right? – Marco Stramezzi Mar 6 '17 at 8:03
  • @MarcoStramezzi that would protect the initialization but not the usage (i.e. any mutable data in the B instance). It depends on your needs. – Frank Hileman Mar 6 '17 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.