Registry pattern
Key 9: Adding functionality from anywhere in code to class.
This is one of my favorite patterns and comes to help a lot. In this pattern, we register classes to a registry, which tracks the naming to functionality. Hence, we can add functionality to the main class from anywhere in the code. In the following code, Convertor
tracks all convertors from dictionary to Python objects. We can easily add further functionalities to the system using the convertor.register
decorator from anywhere in the code, as follows:
class ConvertError(Exception): """Error raised on errors on conversion""" pass class Convertor(object): def __init__(self,): """create registry for storing method mapping """ self.__registry = {} def to_object(self, data_dict): """convert to python object based on type of dictionary""" dtype = data_dict.get('type', None) if not dtype: raise ConvertError("cannot create object, type not defined...