To understand what the factory pattern is and why it is useful, I will use a simile. Imagine you are a dealership and want to order some cars for your dealership. you have two options…
The first option is akin to the old way of instantiating objects (i.e. a class for Audi(), Honda(), BMW(), etc…). The second option is the factory pattern, it would be achieved by a call such as this Audi myAudi = CarFactory.getCar(“audi”).
Clearly, option two is less cluttered and allows us to have a single point of entry to get any car.
The Factory Pattern requires: an overarching interface, concrete classes that implement the interface, and a class to access and create the concrete classes.
We will create an Animal Factory which will be able to provide us with humans, dogs, and birds
Here is a diagram of our code structure
#programming #design-patterns #java #factory-pattern #tutorial