0204

jelly·2025년 2월 4일

커맨드 패턴의 개요
정의: 커맨드 패턴은 행동 패턴 중 하나로, 요청을 객체로 캡슐화하여 요청의 매개변수화, 요청의 큐잉 및 로그 기록, 요청 실행 취소 기능을 제공합니다 5.
구성 요소:
커맨드(Command): 요청을 수행하는 인터페이스를 정의합니다.
리시버(Receiver): 실제 작업을 수행하는 객체입니다.
인보커(Invoker): 커맨드를 호출하는 객체입니다.
클라이언트(Client): 커맨드를 생성하고 인보커에 설정하는 객체입니다.

#include <iostream>
#include <vector>
#include <memory>

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

// Receiver
class Light {
public:
    void turnOn() {
        std::cout << "Light is ON" << std::endl;
    }
    void turnOff() {
        std::cout << "Light is OFF" << std::endl;
    }
};

// Concrete Command
class TurnOnCommand : public Command {
private:
    Light& light;
public:
    TurnOnCommand(Light& l) : light(l) {}
    void execute() override {
        light.turnOn();
    }
};

class TurnOffCommand : public Command {
private:
    Light& light;
public:
    TurnOffCommand(Light& l) : light(l) {}
    void execute() override {
        light.turnOff();
    }
};

// Invoker
class RemoteControl {
private:
    std::unique_ptr<Command> command;
public:
    void setCommand(Command* cmd) {
        command.reset(cmd);
    }
    void pressButton() {
        if (command) {
            command->execute();
        }
    }
};

// Client
int main() {
    Light livingRoomLight;
    TurnOnCommand turnOn(livingRoomLight);
    TurnOffCommand turnOff(livingRoomLight);

    RemoteControl remote;
    
    remote.setCommand(&turnOn);
    remote.pressButton(); // Light is ON

    remote.setCommand(&turnOff);
    remote.pressButton(); // Light is OFF

    return 0;
}
profile
jelly

0개의 댓글