본문 바로가기

카테고리 없음

cpp 커맨드 패턴

#include <iostream>
#include <memory>

// Command 인터페이스
class Command {
public:
    virtual ~Command() = default;
    virtual void execute() = 0;
};

// Receiver (실제 동작을 수행하는 클래스)
class Light {
public:
    void turnOn() {
        std::cout << "Light is ON\n";
    }
    void turnOff() {
        std::cout << "Light is OFF\n";
    }
};

// ConcreteCommand - 전등 켜기
class LightOnCommand : public Command {
private:
    Light& light;  // Receiver 참조
public:
    LightOnCommand(Light& l) : light(l) {}
    void execute() override {
        light.turnOn();
    }
};

// ConcreteCommand - 전등 끄기
class LightOffCommand : public Command {
private:
    Light& light;
public:
    LightOffCommand(Light& l) : light(l) {}
    void execute() override {
        light.turnOff();
    }
};

// Invoker (커맨드를 실행하는 객체, 리모컨)
class RemoteControl {
private:
    std::unique_ptr<Command> command;  // 소유권 보장
public:
    void setCommand(Command* c) {
        command.reset(c);  // 기존 Command 해제 후 새로운 Command 소유
    }
    void pressButton() {
        if (command) command->execute();
    }
};

// Client
int main() {
    Light livingRoomLight;
    RemoteControl remote;

    // 전등 켜기
    remote.setCommand(new LightOnCommand(livingRoomLight));
    remote.pressButton();

    // 전등 끄기
    remote.setCommand(new LightOffCommand(livingRoomLight));
    remote.pressButton();

    return 0;
}