How can, and which, design patterns help me build the example bellow smartly?
There is a base class that knowns how to build some system commands.
Class BaseCmd(object):
def __init__(self, default_a, default_b):
self.a = default_a
self.b = default_b
self.cmd = None
def _buildCmd(self):
# some algorithm that builds a string based on arguments
if self.cmd:
return self.cmd
self.cmd = algorithm()
return self.cmd
def execute():
raise NotImplementedError
and some of the Commands:
Class CmdA(BaseCmd):
cmd_id = 1
def __init__(self, a, b, c):
super(CmdA, self).__init__(a,b)
self.c = c
def execute(self):
return self._buildCmd()
Class CmdB(BaseCmd):
cmd_id = 2
def __init__(self, a, b, c, d):
super(CmdA, self).__init__(a,b)
self.c = c
self.d = d
def execute(self):
return self._buildCmd()
As I want to maintain my Classes
loosely coupled I have another Class
that have the logic to glue the Commands together on the methods of the Instructions
class:
class Instructions(object):
def __init__(self, strategy=None):
if not strategy:
raise UnboundLocalError("No strategy found!")
def instructionAB(self, a, b, c, d):
cmda = CmdA(a,b,c)
# some logic here
cmdb = CmdB(a, b, c, d)
return self.strategy.do([cmda.execute(), cmdb.execute()])
def instructionA(self, a, b, c, d):
cmda = CmdA(a,b,c)
return self.strategy.do([cmda.execute()])
And of course the strategy Class
Class TCPSocket(object)
def _send(self, cmds):
pass
def do(self, cmds)
return self._send(cmds)
Using this:
instructions = Instructions(strategy=TCPSocket())
instructions.instructionAB(a,b,c,d)
First, should I have a base instruction class and subclass each other instructions instead of have them in methods of one Class?
Is this a good use for strategy pattern? I'm trying to figure out if i can/should apply the Command pattern here. My main goal is to have a good maintainable code and learn a bit more of design patterns.
Aucun commentaire:
Enregistrer un commentaire