Patternite Logo

Writing easily extensible code using Python factory classes


Factory classes take care of complicated object construction logic, making it easy to add new class types as required by the application.


In our example, we're interested in instantiating a guitar object based on its model. We have two models currently, a Stratocaster, and a Les Paul. These guitars are different in their physical properties, sounds, and play styles, so we implement them in their own class.

Normally, we could instantiate the object by simply doing:

guitar = Stratocaster() if guitar_model == "stratocaster" else LesPaul()

But what happens when we want to add another guitar to our lineup, say, a Telecaster? Then we have to find every place in our code where we defined guitar and add in the guitar_model == "telecaster" conditional. This quickly becomes untenable for even small programs, or where the conditional logic is more complex.

The solution is to use a factory class (also known as a "factory function" or "factory method") as shown on line #16 with AutoGuitar. Here, any code that interfaces with AutoGuitar doesn't have to worry about the underlying conditional logic, it simply passes the guitar model as a string and an object instantiated from the correct class is returned. This also makes adding in a Telecaster guitar trivial: we just write another condition in AutoGuitar to check if guitar_model == "telecaster". This only needs to be done once, in the factory class.

Profile picture for duncster

| edited

Patternite © 2021

Patternite Logo