# -*- coding: gbk -*-
# -*- coding: utf-8 -*-
"""
这是命令模式的一个应用场景。(具体的故事情节请见《设计模式之禅》)
@author: Edgar
"""
class AbsGroup(object):
def __init__(self):
self.name = self.__class__.__name__
def find(self):
print '%s, 客户在找你们' % self.name
def add(self):
print '%s, 客户要你们添加一项功能' % self.name
def delete(self):
print '%s, 客户要你们删除一项功能' % self.name
def change(self):
print '%s, 客户要你们改变一项功能' % self.name
def showPlan(self):
print '客户要求%s变更计划' % self.name
class RequirementGroup(AbsGroup):
pass
class CodeGroup(AbsGroup):
pass
class PageGroup(AbsGroup):
pass
class AbsCommand(object):
rg = RequirementGroup()
pg = PageGroup()
cg = CodeGroup()
# test = 1
def execute(self):
pass
class AddRequirement(AbsCommand):
#具体命令类,客户只需要传递一个命令给负责人即可,不需要了解各项目组的内部情况
# def __init__(self):
# self.test = 10
def execute(self):
#题外话!实验证明,如果子类没有覆盖父类属性则子类们引用的父类属性为同一个对象
self.rg.find()
self.rg.add()
self.rg.showPlan()
# print id(self.rg)
# print id(self.test)
class Deletepage(AbsCommand):
def execute(self):
self.pg.find()
self.pg.delete()
self.pg.showPlan()
# print id(self.rg)
# print id(self.test)
class Invoker():
#命令传递者,客户只需要把命令告知这个类,不需要对其他项目组类有了解
def __init__(self, command=None):
self.command = command
def setCommand(self, command):
self.command = command
def action(self):
self.command.execute()
if __name__ == '__main__':
ar = AddRequirement()
xiaosan = Invoker(ar)
xiaosan.action()
dp = Deletepage()
xiaosan.setCommand(dp)
xiaosan.action()
#如果有新的命令,只需要创建一个新命令类并传递给Invoker类即可,程序扩展性极佳。
设计模式之命令模式
最新推荐文章于 2024-01-17 11:19:34 发布