본문 바로가기
{Programing}

Design Pattern - Command

by 탱타로케이 2020. 1. 3.

요청을 객체의 형태로 캡슐화하여 사용자가 보낸 요청을 나중에 이용할 수 있도록 매서드 이름, 매개변수 등 요청에 필요한 정보를 저장 또는 로깅, 취소할 수 있게 하는 패턴이다.

 

command : 실행될 요청에 대한 인터페이스. execute 메서드를 가상함수로 선언해 최상위 부모클래스로 만듦.

Concrete Command : 실제로 실행될 요청 기능을 구현한 클래스. command 클래스를 상속 받아 execute 메서드를 구현.

receiver : Concrete Command에서 구현된 기능을 실행하기 위해 사용하는 클래스.

invoker : 기능 실행을 요청하는 호출 클래스.

client : 어느 시점에 어느 커맨드를 실행할지 결정하는 객체.

 

Command Pattern

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Command{
  public:
   virtual void execute(void) =0;
   virtual ~Command(void){};
};

class Ingredient : public Command {
  public:
   Ingredient(string amount, string ingredient){
      _ingredient = ingredient;
      _amount = amount;
   }
   void execute(void){
      cout << " *Add " << _amount << " of " << _ingredient << endl;
   }
  private:
   string _ingredient;
   string _amount;
};

class Step : public Command {
  public:
   Step(string action, string time){
      _action= action;
      _time= time;
   }
   void execute(void){
      cout << " *" << _action << " for " << _time << endl;
   }
  private:
   string _time;
   string _action;
};

class CmdStack{
  public:
   void add(Command *c) {
      commands.push_back(c);
   }
   void createRecipe(void){
      for(vector<Command*>::size_type x=0;x<commands.size();x++){
         commands[x]->execute();
      }
   }
   void undo(void){
      if(commands.size() >= 1) {
         commands.pop_back();
      }
      else {
         cout << "Can't undo" << endl;
      }
   }
  private:
   vector<Command*> commands;
};

int main(void) {
   CmdStack list;

   //Create ingredients
   Ingredient first("2 tablespoons", "vegetable oil");
   Ingredient second("3 cups", "rice");
   Ingredient third("1 bottle","Ketchup");
   Ingredient fourth("4 ounces", "peas");
   Ingredient fifth("1 teaspoon", "soy sauce");

   //Create Step
   Step step("Stir-fry","3-4 minutes");

   //Create Recipe
   cout << "Recipe for simple Fried Rice" << endl;
   list.add(&first);
   list.add(&second);
   list.add(&step);
   list.add(&third);
   list.undo();
   list.add(&fourth);
   list.add(&fifth);
   list.createRecipe();
   cout << "Enjoy!" << endl;
   return 0;
}

위의 코드에서

 

Command = class Command

Concrete Command = class Ingredient , class Step

Invoker = CmdStack

receiver = 여기에선 cout 출력. 보통은 대상 클래스 객체가 있음.

Client = main function

 

Client가 Invoker를 작동시킴.

Client가 Concrete Command 생성함.

Invoker에 Concrete Command가 등록됨.

Concrete Command는 receiver에 전달.

receiver는 실행함.

 

 

'{Programing}' 카테고리의 다른 글

아두이노 프로젝트 리스트  (0) 2021.05.03
Design Pattern  (0) 2020.01.03

댓글