1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonでデザインパターンの「Command」を実装する。

Posted at

GoFのデザインパターン「Command」をpythonで書くときのためのテンプレートです。

command
 └─command.py
main.py
command.py
from abc import ABCMeta, abstractmethod

#命令のインタフェース(API)を定義する役。
class Command(metaclass=ABCMeta):
    @abstractmethod
    def execute(self):
        pass

    @abstractmethod
    def display(self):
        pass

#ConcreteCommand役の命令を実行するときに対象となる役。つまり、命令の受け取り手。例:複合機
class Receiver(object):
    def DoSomething1(self, arg1):
        print("{0}引数を指定して、DoSomething1コマンドを受領。".format(arg1))

    def DoSomething2(self, arg1, arg2):
        print("{0}と{1}引数を指定して、DoSomething2コマンドを受領。".format(arg1,arg2))


#Invokerは命令の実行を開始する役です。Command役で定義されているインタフェースを呼び出す役。例:印刷キュー
#コマンドをリストに格納することで、コマンドの実行履歴を管理できる。
class Invoker(Command):
    def __init__(self):
        self.__cmds = []

    def append_cmd(self, cmd):
        self.__cmds.append(cmd)

    def execute(self):
        for cmd in self.__cmds:
            cmd.execute()
    
    def display(self):
        for cmd in self.__cmds:
            cmd.display()


#Command役のインタフェースを実際に実装している役です。(ConcreteCommand1とConcreteCommand2) 例:印刷対象書類
class ConcreteCommand1(Command):
    def __init__(self, arg1, receiverObj):
        self.__arg1 = arg1
        self.__receiver = receiverObj

    def execute(self):
        self.__receiver.DoSomething1(self.__arg1)

    def display(self):
        print("実効内容 {0}".format(self.__arg1))


class ConcreteCommand2(Command):
    def __init__(self, arg1, arg2, receiverObj):
        self.__arg1 = arg1
        self.__arg2 = arg2
        self.__receiver = receiverObj

    def execute(self):
        self.__receiver.DoSomething2(self.__arg1, self.__arg2)

    def display(self):
        arg2 = format(self.__arg2)
        print("実効内容  {0} {1}".format(arg2, self.__arg1))
main.py
import sys
from command.command import Receiver, Invoker, ConcreteCommand1, ConcreteCommand2


def startMain(arg1, arg2):
    recv = Receiver()
    inv = Invoker()
    inv.append_cmd(ConcreteCommand1(arg1, recv))
    inv.append_cmd(ConcreteCommand2(arg1, arg2, recv))
    inv.execute()
    inv.display()


if __name__ == "__main__":
    startMain(sys.argv[1], sys.argv[2])
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?