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…

  1. Contact a different factory for each type of car you want to get (Audi, Ford, Honda, Ferrari etc…) and tell each one how many cars you want them to create.
  2. Contact a single factory but tell them what type of car you want as well as how many you want

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.

What will we build?

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

Image for post

#programming #design-patterns #java #factory-pattern #tutorial

Learn The Factory Pattern In A Clean Simple Animal Application
1.05 GEEK