Design Patterns/Behavioral Patterns

Command Pattern (C++)

개발새발 2019. 12. 22. 13:01
반응형

Command Pattern (명령 패턴)

목적

Client가 어떤 기능에 대한 요청을 할 때 요청을 직접 호출하지 않고 요청자체를 캡슐화한다.

명령 패턴의 핵심은 연산을 실행하는 데 필요한 인터페이스를 선언해 놓은 Command 추상 클래스이다.

Client입장에서는 필요한 구체화된 Command만 설정해주면 된다.

 

사용 시나리오

  • Iot 허브가 있고 허브에서 연결된 things를 제어한다고 가정한다.
  • Iot허브는 Invoker가 되고 things는 Receiver가 된다.
  • things 각각의 명령어를 command로 구체화 한다.
  • 해당 예에서는 IoT기능이 있는 IotTV를 Command패턴을 통해 제어하는 예이다.

[Receiver]

class IotTV { //Receiver
public:
    void turnOn() {
        cout<<"Turn on Iot TV"<<endl;
    }
    void turnOff() {
        cout<<"Turn off Iot TV"<<endl;
    }
};

[Command]

class Command { //Command Interface
public:
    virtual void excute() = 0;
    virtual ~Command() {}
};

[ConcreteCommand]

class IotTVOnCommand : public Command {
public:
    IotTVOnCommand(IotTV* iotTV) {
        this->iotTV = iotTV;
    }
    void excute() override {
        iotTV->turnOn();
    }
    
private:
    IotTV* iotTV;
};

class IotTVOffCommand : public Command {
public:
    IotTVOffCommand(IotTV* iotTV) {
        this->iotTV = iotTV;
    }
    void excute() override {
        iotTV->turnOff();
    }
    
private:
    IotTV* iotTV;
};

[Invoker]

class IotInvoker {
public:
    void setCommand(Command* command) {
        this->command = command;
    }
    void runCommand() {
        if(command)
            command->excute();
    }

private:
    Command* command;
};

[Client]

int main(int argc, const char * argv[]) {
    IotTV* iotTV = new IotTV();
    
    IotTVOnCommand* iotTVOnCommand = new IotTVOnCommand(iotTV);
    IotTVOffCommand* iotTVOffCommand = new IotTVOffCommand(iotTV);
    
    IotInvoker* iotInvoker = new IotInvoker();
    iotInvoker->setCommand(iotTVOnCommand);
    iotInvoker->runCommand();
    
    iotInvoker->setCommand(iotTVOffCommand);
    iotInvoker->runCommand();
    
    delete iotInvoker;
    delete iotTVOffCommand;
    delete iotTVOnCommand;
    delete iotTV;
    return 0;
}

 

실행결과

Turn on Iot TV

Turn off Iot TV

 

 

반응형