In general implementation of factory is as follows:
- Create interface defining methods based on the interface type. Here since your interface is for implementing Web Protocol Service, methods would be related to the functionalities you want to expose to the world to use. Try to keep as generic as possible. This interface will have a abstract method called protocolType() which will be implemented by different classes based on protocol type. Here HTTP or SOCKET.
To Create an interface in Python you can use formal interface - ABC.
import abc.ABC, abc.abstractmethod
# I am omitting __init__ implementation of this class, that is self explanatory
class WebProtocol(ABC):
@abstractmethod
def abstract_method_1(self):
pass
@abstractmethod
def protocol_type(self):
pass
Extend your implementation of HTTP or SOCKET based protocols with WebProtocol interface.
For reference checkout: http://masnun.rocks/2017/04/15/interfaces-in-python-protocols-and-abcs/
- Create a Factory class which will be responsible for managing and providing appropriate Web Protocol Service implementation based on the protocol type. This factory will majorly have 2 methods.
a. provide(Web Protocol Type);
This factory will hold a map, mapping every implementation of the WebProtocol interface to its Protocol Type, which is get registered in init function.
Again here create a Factory interface, exposing main functions of of a factory class. i.e. provide
import abc.ABC, abc.abstractmethod
# I am omitting __init__ implementation of this class, that is self explanatory
class Factory(ABC):
@property
factory = {}
def provide(self, factory_type):
'''
This method is for providing implementations based on protocolType from the
factory
'''
factory.get(factory_type, None)
import Factory
# I am omitting __init__ implementation of this class, that is self explanatory
class WebProtocolFactory(Factory):
factory = {}
def __init__(self):
factory['HTTP'] = HttpWebProtocol()
factory['SOCKET'] = SocketWebProtocol()
- Whenever you want any specific implementation of WebProtocol Service, just use factory's provide function(ProtocolType) to retrieve specific implementation based on Protocol Type.
import WebProtocolFactory
#For using the factory
webProtocolFactory = WebProtocolFactory()
httpWebProtocol = webProtocolFactory.provide('HTTP')
socketProtocolFactory = webProtocolFactory.provide('SOCKET')
- If at later stage any new Protocols adds, just create an implementation of that protocol, and get is registered in the factory but adding in init function.