LoginSignup
11
8

More than 5 years have passed since last update.

【デザインパターン】 Commandパターン

Posted at

概要

命令とそれに伴うパラメータをカプセル化したパターン

以下の5種類のクラスからなる
1. Commandクラス(命令のインタフェースを定義)
2. ConcreteCommandクラス(1.のインタフェースを実装)
3. Clientクラス(2.を生成してそれに対する5.を設定する)
4. Invokerクラス(1.で定義されているインタフェースを呼び出す)
5. Receiverクラス(1.の処理対象となるオブジェクトのインタフェース)

具体例と実装

家事手伝いロボットを例にすると、

上記1~5はそれぞれ

  1. 命令クラス(Commandクラス、家事を行うための命令)
  2. 掃除クラス、洗濯クラス、炊事クラス(CleanUpCommandクラス、WashingCommandクラス、CookingCommandクラス、掃除、洗濯、炊事の命令のクラス)
  3. ロボット所有者クラス(RobotUserクラス、家事手伝いロボットの所有者)
  4. 命令入力用リモコンクラス(Controllerクラス、家事手伝いロボットへの命令を出す) 5.家事手伝いロボットクラス(HouseWorkRobbotクラス、家事手伝いロボット)

が対応する。
コードの詳細は以下

command.rb
class Command
  def initialize
    @robot = HouseWorkRobbot.new()
  end

  def do()
  end

  def cancel()
  end
end
clean_up_command.rb
class CleanUpCommand < Command
  def do()
    @robot.do_clean_up
  end

  def cancel()
    @robot.cancel_clean_up
  end
end
washing_command.rb
class WashingCommand < Command
  def do()
    @robot.do_washing
  end

  def cancel()
    @robot.cancel_washing
  end
end
cooking_command.rb
class CookingCommand < Command
  def do()
    @robot.do_cooking
  end

  def cancel()
    @robbot.cancel_cooking
  end
end
robot_user.rb
class RobotUser
  def initialize()
    @controller = Controller.new
  end

  def clean_up()
    @controller.clean_up()
  end

  def washing()
    @controller.washing()
  end

  def cooking()
    @controller.cooking()
  end

  def cancel()
    @controller.cancel()
  end
end
controller.rb
class Controller
  def clean_up
    clean_up_command = CleanUpCommand.new
    do(clean_up_command)
  end

  def washing
    washing_command = WashingCommand.new
    do(washing_command)
  end

  def cooking
    cooking_command = CookingCommand.new
    do(cooking_command)
  end

  def cancel
    @previous_command.cancel()
  end

  private

  def do(command)
    command.do
    @previous_command = command
  end
end
house_work_robbot
class HouseWorkRobot
  def do_clean_up
   # 掃除をする
  end

  def cancel_clean_up
    # 掃除をやめる
  end

  def do_washing
   # 洗濯をする
  end

  def cancel_washing
    # 洗濯をやめる
  end

  def do_cooking
   # 炊事をする
  end

  def cancel_cooking
    # 炊事をやめる
  end
end

メリット

  • オペレーションの呼び出しをするオブジェクトと実行するオブジェクトを分離する
  • 複数のCommandオブジェクトを合成することが出来る
  • 新しいCommandの追加が容易に行える

まとめ

オブジェクトに対する要求自体をオブジェクトにすることで、あるオブジェクトに対して複数の要求を組み合わせて送りたいときに便利なパターン

11
8
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
11
8