Python中的常规命令模式和命令调度模式 [英] General Command pattern and Command Dispatch pattern in Python

查看:92
本文介绍了Python中的常规命令模式和命令调度模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找Python中的 Command 模式实现... (根据维基百科

I was looking for a Command pattern implementation in Python... (According to Wikipedia,

命令模式是设计 对象用于的模式 表示并封装所有 在以下位置调用方法所需的信息 以后.

the command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time.

)

我发现的唯一东西是命令调度 pattern :

The only thing I found was Command Dispatch pattern:

class Dispatcher:

    def do_get(self): ...

    def do_put(self): ...

    def error(self): ...

    def dispatch(self, command):
        mname = 'do_' + command
        if hasattr(self, mname):
            method = getattr(self, mname)
            method()
        else:
            self.error()

可能是我错了,但看起来这是两个不同的概念,偶然有相似的名字.

May be I'm wrong, but it looks like these are two different concepts, which accidentally have similar names.

我想念什么吗?

推荐答案

最简单的命令模式已经内置在Python中,只需使用可调用对象即可:

The simplest command pattern is already built into Python, simply use a callable:

def greet(who):
    print "Hello %s" % who

greet_command = lambda: greet("World")
# pass the callable around, and invoke it later
greet_command()

如果您的命令需要执行的功能不仅仅被调用,那么将命令模式作为一种面向对象的设计模式更有意义.常见用例是当您需要能够撤消/重做操作时.然后,命令类是将前进和后退动作耦合在一起的好方法.例如:

The command pattern as an object oriented design pattern makes more sense if your commands need to be able to do more than just be invoked. Common usecase is when you need to be able to undo/redo your actions. Then a command class is a good way to couple the forward and backwards actions together. For example:

class MoveFileCommand(object):
    def __init__(self, src, dest):
        self.src = src
        self.dest = dest
        os.rename(self.src, self.dest)
    def undo(self):
        os.rename(self.dest, self.src)

undo_stack = []
undo_stack.append(MoveFileCommand('foo.txt', 'bar.txt'))
undo_stack.append(MoveFileCommand('bar.txt', 'baz.txt'))
# foo.txt is now renamed to baz.txt
undo_stack.pop().undo() # Now it's bar.txt
undo_stack.pop().undo() # and back to foo.txt

这篇关于Python中的常规命令模式和命令调度模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆