프로그래밍/GoF

[행동 패턴] - 명령(Command)

MAKGA 2022. 1. 5. 19:45
320x100

구조

#include <iostream>
#include <string>
#include <queue>

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

class Receiver
{
public:
    void action() {
        std::cout << "Receiver action" << std::endl;
    }
};

class DerivedCommand final : public Command
{
public:
    DerivedCommand(Receiver* receiver)
        :receiver_(receiver)
    {
    }

    void execute() override final
    {
        std::cout << "DerivedCommand execute" << std::endl;
        receiver_->action();
    }

private:
    Receiver* receiver_;
};

class Invoker
{
public:
    Invoker() = default;

    void storeCommand(Command* command)
    {
        commands.push(command);
        command->execute();
    }

private:
    std::queue<Command*> commands;
};

 

실행

int main()
{
    Receiver* receiver = new Receiver();
    Command* command = new DerivedCommand(receiver);
    Invoker* invoker = new Invoker();

    invoker->storeCommand(command);

    return 0;
}

 

Invoker에 동작할 동작(receiver)를 넣은 Command를 목록으로 유지해서 undo같은 기능을 구현한다고 하는데

어디다가 쓸지 감은 잘 안온다.

 


320x100