// ConsoleApplication19.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
/*
是一个抽象类,类中对需要执行的命令进行声明,
一般来说要对外公布一个execute方法用来执行命令*/
class Command
{
public:
virtual void execute()=0; //C++声明纯虚函数才可以重载?
};
//调用者 负责调用命令
class Invoker
{
private:
Command *command;
public:
void SetCommand(Command *c)
{
this->command = c;
}
void Action()
{
this->command->execute();
}
};
//接收者 负责接收命令并且执行
class Receiver
{
public:
void DoSomething()
{
cout<<"接受-业务逻辑处理"<<endl;
}
};
//具体的command实现类
class ConcreteCommand:public Command
{
private:
Receiver *receiver;
public:
ConcreteCommand(Receiver *r)
{
this->receiver = r;
}
void execute()
{
this->receiver->DoSomething();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Receiver *r = new Receiver();
Command *command = new ConcreteCommand(r);
Invoker *invoker = new Invoker();
invoker->SetCommand(command);
invoker->Action();
return 0;
}
命令模式
最新推荐文章于 2024-06-29 20:06:35 发布