以前在github给自己写日记习惯了,现在csdn写东西还是要更加规范点,以后还是写完全能编译的代码吧!
#include <iostream>
#include <stdlib.h>
#include <string>
#include <list>
#include <vector>
#include <map>
using std::map;
using std::endl;
using std::cout;
using std::list;
using std::vector;
using std::string;
//命令模式
//作者前面的设计感觉可以归纳为,类的函数封装与类之间的父子关系。
//最近的两个模式让我觉得,作者已经开始进入;类与类的关系,类与类的调用与封装了。
//先看命令模式的示例: 需求组、美工组、代码组、客户类每增加一个需求就会多次无序调用这三个组
//所以需要设计一个类似中介的类
class Group {
//抽象组类,作者一贯习惯
public:
virtual void Find() = 0;
virtual void Add() = 0;
virtual void Delete() = 0;
virtual void Change() = 0;
virtual void Plan() = 0;
};
//分别实现三组
class RequirementGroup : public Group {
public:
void Find() {
cout << "require find" << endl;
}
void Add() {
cout << "require add" << endl;
}
void Change() {
cout << "require change" << endl;
}
void Plan() {
cout << "require plan" << endl;
}
void Delete() {
cout << "require delete" << endl;
}
};
class PageGroup : public Group {
public:
void Find() {
cout << "page find" << endl;
}
void Add() {
cout << "page add" << endl;
}
void Change() {
cout << "page change" << endl;
}
void Plan() {
cout << "page plan" << endl;
}
void Delete() {
cout << "page delete" << endl;
}
};
class CodeGroup : public Group {
public:
void Find() {
cout << "code find" << endl;
}
void Add() {
cout << "code add" << endl;
}
void Change() {
cout << "code change" << endl;
}
void Plan() {
cout << "code plan" << endl;
}
void Delete() {
cout << "code delete" << endl;
}
};
//封装客户的命令,产生命令类
class Command {
protected:
RequirementGroup* p_rg;
PageGroup* p_pg;
CodeGroup* p_cg;
public:
Command()
: p_rg(new RequirementGroup)
, p_pg(new PageGroup)
, p_cg(new CodeGroup){}
virtual void execute() = 0;
};
class AddRequirementCommand : public Command {
public:
//客户添加需求
void execute() {
p_rg->Find();
p_rg->Add();
p_rg->Plan();
}
};
class DeletePageCommand : public Command {
public:
void execute() {
p_pg->Find();
p_rg->Delete();
p_rg->Plan();
}
};
class Invoker {
private:
Command* p_command;
public:
void SetCommand(Command* p_c) {
p_command = p_c;
}
void action() {
p_command->execute();
}
};
class Client {
public:
static void Main() {
//删除页面操作
Invoker* p_in = new Invoker;
Command* p_co = new DeletePageCommand;
p_in->SetCommand(p_co);
p_in->action();
}
};
<span style="font-family: Arial, Helvetica, sans-serif;">//命令模式基本三个角色</span>
<pre name="code" class="cpp">//接收者(工作组)、命令者(command)、调用者(invoker).都要看情况设置抽象类和具体类
//扩展,添加命令就好
int _tmain(int argc, _TCHAR* argv[])
{
Client::Main();
system("pause");
return 0;
}