意图:
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;
对请求排队或记录请求日志,以及可支持的撤销操作
适用性:
1抽象出待执行的动作以参数化某对象,可用过程语言中的回调函数表达这种参数化机制。Command模式是回调机制的一个面向对象的替代品
2在不同的时刻指定,排列和执行请求
3支持取消操作
4支持修改日志
5用构建在原语操作上的高层操作构造一个系统
效果:
1将调用操作的对象与知道如何实现该操作的对象解耦合
2可将多个命令装配成一个复合命令
3很容易增加新的Command
Command.h
- #include <iostream>
- using namespace std;
- class Command
- {
- public:
- virtual ~Command() {cout<<"Command is destroyed"<<endl;}
- virtual void Execute() = 0;
- };
- class Document
- {
- public:
- Document(const char* s){cout<<"A document is created"<<endl;}
- void Open(){cout<<"Open the document"<<endl;}
- void Paste(){cout<<"Paste the document"<<endl;}
- //Action* _action;
- private:
- char* _doc;
- };
- class Application
- {
- public:
- Application(){cout<<"An application is created"<<endl;}
- Add(Document* ){cout<<"Add an Doucment to the Application"<<endl;}
- };
- class OpenCommand:public Command
- {
- public:
- OpenCommand(Application*);
- virtual void Execute();
- protected:
- virtual const char* AskUser();
- private:
- Application* _application;
- char* _response;
- };
- class PasteCommand:public Command
- {
- public:
- PasteCommand(Document* doc){_document = doc;}
- virtual void Execute() {_document->Paste();}
- private:
- Document* _document;
- };
- template <class Receiver>
- class SimpleCommand:public Command
- {
- public:
- typedef void (Receiver::*Action)();
- SimpleCommand(Receiver* r,Action a):_receiver(r), _action(a)
- {
- }
- SimpleCommand(Receiver* r,const char* s):_receiver(r), _action(s)
- {
- }
- SimpleCommand(Receiver* r):_receiver(r)
- {
- }
- virtual void Execute();
- private:
- Action _action;
- Receiver* _receiver;
- };
- template <class Receiver> void SimpleCommand<Receiver>::Execute()
- {
- _receiver->Paste();
- }
Command.cpp
- #include <iostream>
- using namespace std;
- #include "Command.h"
- OpenCommand::OpenCommand(Application* a)
- {
- _application = a;
- }
- void OpenCommand::Execute()
- {
- const char* name = AskUser();
- if (name != 0)
- {
- Document* document = new Document(name);
- _application->Add(document);
- document->Open();
- }
- }
- const char* OpenCommand::AskUser()
- {
- char* s="1234";
- return s;
- }
main.cpp
- #include "Command.h"
- #include <iostream>
- using namespace std;
- int main()
- {
- Document* receiver = new Document("1234");
- Command* aCommand = new SimpleCommand <Document>(receiver,&Document::Paste);
- aCommand->Execute();
- return 0;
- }