Python 設計模式 - 命令



命令模式在操作之間增加了一層抽象,幷包含了一個物件,該物件呼叫這些操作。

在此設計模式中,客戶端建立一個命令物件,其中包括要執行的命令列表。建立的命令物件實現了特定介面。

以下是命令模式的基本架構:--

Architecture of Command Pattern

如何實現命令模式?

現在我們將瞭解如何實現設計模式。

def demo(a,b,c):
   print 'a:',a
   print 'b:',b
   print 'c:',c

class Command:
   def __init__(self, cmd, *args):
      self._cmd=cmd
      self._args=args

   def __call__(self, *args):
      return apply(self._cmd, self._args+args)
cmd = Command(dir,__builtins__)
print cmd()

cmd = Command(demo,1,2)
cmd(3)

輸出

以上程式生成以下輸出:--

Command Pattern

說明

該輸出實現了 Python 語言中列出的所有命令和關鍵字。它列印變數的必要值。

廣告