COMMAND 명령 패턴
- 요청을 객체 형태로 캡슐화 시킨다.
- 콜백을 객체지향으로 표현한 것.
#include <iostream> using namespace std; class Receiver{ public: void action() { cout << "Receiver" << endl; } }; class Command{ public: virtual void execute() = 0; }; class ConcreteCommnad : public Command{ public: void setReceiver(Receiver* r) { _receiver = r; } void execute() { _receiver->action(); } private: Receiver* _receiver; }; class Invoker{ public: void SetCommand(Command* c) { _command = c; } void Execute() { _command->execute(); } private: Command* _command; }; int main(){ Invoker invoker; Receiver receiver; ConcreteCommnad concretecommand; concretecommand.setReceiver(&receiver); invoker.SetCommand(&concretecommand); invoker.Execute(); return 0; }
// Command 클래스를 template 시켜 Invoke를 사용하지 않음. class Receiver{ public: virtual void action() = 0; }; class ConcreteClass1 : public Receiver{ public: void action() { cout << "ABCDE" << endl; } }; class ConcreteClass2 : public Receiver{ public: void action() { cout << "12345" << endl; } }; template<typename T> class Command{ public: Command(T* r) : _receiver(r) {} ~Command() { if(_receiver) delete _receiver; } void excute() { _receiver->action(); } private: T* _receiver; }; int main(){ Command<ConcreteClass1> command1(new ConcreteClass1()); Command<ConcreteClass2> command2(new ConcreteClass2()); command1.excute(); command2.excute(); return 0; }
'Study > Design Patterns c++' 카테고리의 다른 글
Design Patterns CHAIN OF RESPONSIBILITY 책임 연쇄 패턴 패턴 C++ (0) | 2018.07.03 |
---|---|
Design Patterns ABSTRACT FACTORY 추상 팩토리 패턴 C++ (0) | 2018.07.03 |
Design Patterns PROXY 프록시 패턴 C++ (0) | 2018.07.02 |
Design Patterns FLYWEIGHT 플라이급 패턴 패턴 C++ (0) | 2018.07.02 |
Design Patterns FACADE 퍼사드 패턴 C++ (0) | 2018.06.19 |