命令模式(python)

  命令模式:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;支持对请求排队、记录请求日志,以及可撤销的操作。

优点:把请求一个操作的对象与知道怎么执行一个操作的对象分隔开。

#encoding=utf-8

#

#by panda

#命令模式

def printInfo(info):

    print unicode(info, 'utf-8').encode('gbk')

import time

#Command

class Command():

    receiver = None

    def __init__(self, receiver):

        self.receiver = receiver

    def Execute(self):

        pass    

#具体命令类:拷羊肉串

class BakeMuttonCommand(Command):

    def SetHandsetSoft(self, receiver):

        Command.__init__(self,receiver)

    def Execute(self):

        self.receiver.BakeMutton()   

    def ToString(self):

        return '拷羊肉串'

#具体命令类:拷鸡翅

class BakeChickenWingCommand(Command):

    def SetHandsetSoft(self, receiver):

        Command.__init__(self,receiver)

    def Execute(self):

        self.receiver.BakeChickenWing()   

    def ToString(self):

        return '拷鸡翅'

#Receiver:拷肉串的人

class Barbecuer(): 

    def BakeChickenWing(self):

        printInfo('拷鸡翅!')

    def BakeMutton(self):

        printInfo('拷羊肉串!')

#Invoker:服务员

class Waiter():

    commandList = []

    def SetOrder(self,command):

        printInfo('%s 增加订单:%s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),command.ToString()))

        self.commandList.append(command)

    def CancelOrder(self,command):

        printInfo('%s 取消订单:%s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),command.ToString()))

        self.commandList.remove(command)

    def Notify(self):

        printInfo('\n通知:')

        for command in self.commandList:

            command.Execute()

    def Run(self):

        printInfo('运行手机通信录')

def clientUI():

    boy = Barbecuer()

    bakeMuttonCommand1 = BakeMuttonCommand(boy)

    bakeMuttonCommand2 = BakeMuttonCommand(boy)

    bakeChickenWingCommand1 = BakeChickenWingCommand(boy)

    girl = Waiter()

    girl.SetOrder(bakeMuttonCommand1)

    girl.SetOrder(bakeMuttonCommand2)

    girl.SetOrder(bakeChickenWingCommand1)

    girl.CancelOrder(bakeMuttonCommand1)

    girl.Notify()

    return

if __name__ == '__main__':

    clientUI();

类图:

\

posted @ 2013-07-30 10:48  草根儿  阅读(124)  评论(0编辑  收藏  举报