设计模式笔记--行为型模式之二--Command
2008-09-07 18:55
405 查看
意图:
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;
对请求排队或记录请求日志,以及可支持的撤销操作
适用性:
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;
}
相关文章推荐
- 设计模式笔记 14. Command 命令模式(行为型模式)
- 设计模式学习笔记:看着挺像的Strategy Bridge Command
- 设计模式笔记--创建型模式之二 Builder
- 设计模式之对象行为型模式 — COMMAND (命令)模式
- 设计模式笔记(16)---解释器模式(行为型)
- 设计模式--命令模式Command(对象行为型)
- 设计模式笔记(17)---中介者模式(行为型)
- 设计模式 ( 十三 ) 命令模式Command(对象行为型)
- 设计模式笔记(18)---迭代器模式(行为型)
- 设计模式笔记(19)---观察者模式(行为型)
- [设计模式笔记]三. 行为型模式--16. Command模式(命令模式)(一)
- 设计模式(4)-行为型-命令模式(Command)
- 步步为营 .NET 设计模式学习笔记 九、Command(命令模式)
- JAVA设计模式(15):行为型-命令模式(Command)
- 学习Java 23种设计模式详解笔记之行为型模式(三)
- 设计模式深入学习--Command 命令模式(行为型模式)
- java 设计模式学习笔记十二 command命令设计模式
- 设计模式学习笔记:行为型模式
- 设计模式——行为型模式之 Command 命令模式
- 设计模式笔记 17. Iterator 迭代器模式(行为型模式)