C++ The Modern Factory

Legacy Factory


Classical aka “Legacy” Factory Pattern. Looking at the diagram this seems very simple and obvious. For this post we will use the real life use-case of the “Car Factory”.  In particular to try and explain the architectural issues.

Now consider this.  Using the architecture above, how would you serve contemporary customers and offer them “build your own car” service?  Some on line page, where customers start with some half finished base of the car and then  pick and mix variety of engines, headlights, wheels, seats, sun roof etc … all the way to the details like in-car sound and vision, and a such.

Architecture above is made for factories that deliver ready made, possibly pre-built, finished cars. It is surely possible to re organize  the  internals of the factory to  make different variations to each model, but there is a practical limit. The more customers can pick-n-mix, the number of ever so different models raises exponentially.

The inherent flaw in this architecture is high level of abstraction granularity. Which in turn greatly lowers the level of architecture flexibility and resilience to change.

Implementation issues

I have come to the conclusion, in each Factory pattern variations, the actual factory method, class or whatever, is the focal point of quality issues, where one can feel the design on top of which the implementation resides.

Here is the factory method of the classical factory.

What is wrong with this code? Not much. It is only that this is almost C++98.

As the only modern thing, car_smart_pointer is usually implemented with  std::shared_ptr ; with us at least since C++11, which was standard since Aug 2011 (gasp!) But there where many quality smart pointer implementations before that. (Of course, I do not mean std::smart_ptr ).

We need to use the (smart) pointer here. It is not possible to return instance of Abstract Base Class. And this is how IAutomobile is implemented.

And then we implement our two car models by simply inheriting from this ABC.

class cabriolet from the diagram is almost the same. This is where we meet head-on, two things I do not like :

  • Inheritance
  • Code repetition

And then we invent clever design and then we “invent” coding idioms to mitigate the issues of these two.   If you are by now, standing in shock or are in hot disagreement, please refer to numerous on-line discussions on classical factory pattern implementation issues.

I particularly like Sean Parent’s  Inheritance Is The Base Class of Evil. It is about that and much more important things. Every minute is  full of quality c++ and quality design decisions. Not easy to follow but worth it.