I understand the Java and C++ code examples of how a factory pattern works, though I've never coded in Java and haven't coded in C++ for almost 2 decades. I just need to understand the concept in order to follow some API documentation.
What I'm having trouble understanding is the use case. Most explanations say that if you use a factory method to create objects of a derived class based on the value of one of its arguments, it makes it easier to expand the number of derived classes. At a high level, I understand the words, but I haven't found a code example of when the absence of a factory is a problem. The only attempt I could find of showing the problem at a code level is here.
There are a number of issues with example, as noted in the comments to this question. However, I'd like to set them aside and focus on the problem that the factory is meant to solve.
The cited code is separated into (i) library code for a Vehicle
base class and (ii) client code to instantiate a specific Vehicle
subclass representing (say) a TwoWheeler
or a ThreeWheeler
. The problem solution is that if you add a new subclass to the set of existing subclasses, you don't need to rejig any client-side code. But the example Client
class is too trivial to see what the problem is. The exact Vehicle
subclass specification is hard coded into the Client class definition. Anywhere where Client is used to create an object, one could just as easily create an object of the specified subclass.
I get that the example has to be simple so that one can see through the code and syntax, and understand the reasoning. But the logic depicted still seems to focus on the mechanics of a factory, and it doesn't depict a real need for the factory.
Can anyone point to an online code-level example showing an realistic need for a factory?
I'm still working through a series of links that I've saved, but frankly, there seems to be a tendency to show mechanics of the factory pattern at the code level, while explaining the justifying need only at a narrative level. Hopefully, a code-level example of a realistic need for a factory is still small.
Thanks.