学习版本3.5.2
命令模式:将请求封装成对象,以便使用不同的请求、日志、队列等来参数化其它对象。命令模式也支持撤销操作。
#学习版本3.5.2
'''命令模式举例:将军通过传令兵来命令士兵攻击或者防守'''
#命令
class Command(object):
def __init__(self):
self.name = "Command"
#执行命令
def execute(self):
print("executive command:", self.name)
class Attack(Command):
def __init__(self):
self.name = "Attack"
class Defend(Command):
def __init__(self):
self.name = "Defend"
class AttackCancel(Command):
def __init__(self):
self.name = "AttackCancel"
class DefendCancel(Command):
def __init__(self):
self.name = "DefendCancel"
#将军
class General(object):
def __init__(self, messenger):
self._messenger = messenger
#发号施令
def sendCommand(self, command):
self._messenger.sendCommand(command)
#传令兵
class Messenger(object):
def __init__(self):
self.soldierslist = []
def setSoldiersList(self, soldier):
self.soldierslist.append(soldier)
#将命令传达给士兵
def sendCommand(self, command):
for s in self.soldierslist:
s.execute(command)
#士兵
class Soldier(object):
def __init__(self, name):
self.name = name
#士兵执行命令
def execute(self, command):
print(self.name)
command.execute()
if __name__ == "__main__":
s1 = Soldier("s1")
s2 = Soldier("s2")
m = Messenger()
m.setSoldiersList(s1)
m.setSoldiersList(s2)
general = General(m)
general.sendCommand(Attack())
general.sendCommand(Defend())
运行结果
s1
executive command: Attack
s2
executive command: Attack
s1
executive command: Defend
s2
executive command: Defend