Reputation: 12018
I am very new to Python and I want to implement the factory pattern using Python classes.
I want to implement an abstraction for two different types of communication channels. For example, socket and HTTP.
I want to keep the interface the same for communication with these two communication channels from the main application. So that there will be minimal change in the application if a new communication channel gets added.
What is the best way to implement this in Python? Any reference will help.
Upvotes: 0
Views: 393
Reputation: 129
In general implementation of factory is as follows:
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/
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()
import WebProtocolFactory
#For using the factory
webProtocolFactory = WebProtocolFactory()
httpWebProtocol = webProtocolFactory.provide('HTTP')
socketProtocolFactory = webProtocolFactory.provide('SOCKET')
Upvotes: 2