设计模式之命令模式
from abc import ABCMeta, abstractmethod # 命令模式四个角色:命令、接收者、调度者、用户 # 对命令的发送者和接收者进行解耦,高内聚 # 其中的调度者有点像Scrapy框架中的Scheduler,对请求和响应进行调度 class Command(metaclass=ABCMeta): """命令的抽象类""" @abstractmethod def execute(self): pass class CommandImpl(Command): """命令的具体实现类""" def __init__(self, receiver): self.__receiver = receiver def execute(self): self.__receiver.doSomethig() class Receiver: """命令的接收者""" def doSomethig(self): print("do Something...") class Invoker: """调度者""" def __init__(self): self.__command = None def setCommand(self, command): self.__command = command def action(self): if self.__command is not None: self.command.execute() # 实战应用 class GameRole: """游戏的角色""" STEP = 5 def __init__(self, name): self.__name = name self.__x = 0 self.__y = y self.__z = z def leftMove(self): self.__x -= self.STEP def rightMove(self): self.__x += self.STEP def upMove(self): self.__y += self.STEP def downMove(self): self.__y -= self.STEP def jumpMove(self): self.__z += self.STEP def squatMove(self): self.__z -= self.STEP def attack(self): print("%s发动了攻击..." % self.__name) def showPosition(self): print("%s 的位置:(x:%s, y:%s, z:%s)" % (self.__name, self.__x, self.__y, self.__z)) class GameCommamd(metaclass=ABCMeta): """游戏角色的命令类""" def __init__(self, role): self.__role = role def setRole(self, role): self.__role = role @abstractmethod def execute(self): pass class Left(GameCommamd): """左移""" def execute(self): self.__role.leftMove() self.__role.showPosition() class Right(GameCommamd): """右移""" def execute(self): self.__role.rightMove() self.__role.showPosition() class Up(GameCommamd): """上移""" def execute(self): self.__role.upMove() self.__role.showPosition() class Down(GameCommamd): """下移""" def execute(self): self.__role.downMove() self.__role.showPosition() class Jump(GameCommamd): """弹跳""" def execute(self): self.__role.jumpMove() self.__role.showPosition() class Squat(GameCommamd): """下蹲""" def execute(self): self.__role.squatMove() self.__role.showPosition() class Attack(GameCommamd): """攻击""" def execute(self): self.__role.attack() self.__role.showPosition() class MacroCommand(GameCommamd): """"组合""" def __init__(self, role=None): super().__init__(role) self.__commands = [] def addCommand(self, command): self.__commands.append(command) def execute(self): for command in self.__commands: command.execute() class GameInvoker: """命令调度者""" def __init__(self): self.__command = None def setCommand(self, command): self.__command = command def action(self): if self.__command is not None: self.__command.execute()