Path: blob/master/python/factory_pattern.ipynb
1470 views
Table of Contents
Factory Design Pattern
Let's look at an example where we need to convert the Song object to a string representation according to a user-specified format parameter.
The code above works fine but can benefit from refactoring. One of the best practices behind writing clean code is Single Responsibility Principle. Here, instead of using a complex if/elif/else conditional structure to determine the concrete implementation, the application delegates that decision to a separate component that creates the concrete object. Then concrete implementation of the interface is identified by some parameter. With this approach, we can have a class/method that does one thing only and one thing well, making it more reusable and easier to maintain.
This type of creational design pattern is so called Factory Design Pattern.
Let's take a look at how we can refactor the code above. The first step when we see complex conditional code in an application is to identify the common goal of each of the execution paths (or logical paths), and separate out implementations for each logical path. With the factory pattern, we let the client, our serialize
method depend on a creator, get_serializer
method, which returns the actual implementation using some sort of identifier.