Factory Method

Factory method comes into picture when there is a method in a class which creates objects. And to customize the creation of those objects, we inherits subclass and override that method.

class StorageManager:
    def create_storage_plugin(self):
        return LocalStorage()

create_storage_plugin method is factory method in class StorageManager. What if we want google cloud storage? We would simply do following,

class GoogleStorageManager(StorageManager):
    def create_storage_plugin(self):
        return GoogleStorage()

This method is mostly used in languages where classes and functions are not first class citizens and they can’t be passed around in as parameters.

We have solve the same problem in pythonic way.

class StorageManager:
    def __init__(self, storage_plugin):
        self.storage_plugin = storage_plugin
    def create_storage_plugin(self):
        return self.storage_plugin()
 
storage_manager = StorageManager(GoogleStorage)
storage_manager = StorageManager(LocalStorage)
storage_manager = StorageManager(NetworkStorage)

This example may not be best suited here, however the idea is same.

References

  1. https://python-patterns.guide/gang-of-four/factory-method/