模板方法模式
#include<iostream>
#include<string>
using namespace std;
class Resume
{
protected:
virtual void writeBasicInfo() = 0;
virtual void writeEducation() = 0;
virtual void writeWorkExperience() = 0;
public:
void FillResume()
{
writeBasicInfo();
writeEducation();
writeWorkExperience();
}
virtual ~Resume() {};
};
class ResumeA : public Resume
{
protected:
void writeBasicInfo()
{
cout << "简历A: 基本信息, ";
}
void writeEducation()
{
cout << "教育背景, ";
}
void writeWorkExperience()
{
cout << "工作经验 (越详细越好)." << endl;
}
};
class ResumeB : public Resume
{
protected:
void writeBasicInfo()
{
cout << "简历B: 基本信息, ";
}
void writeEducation()
{
cout << "教育背景, ";
}
void writeWorkExperience()
{
cout << "工作经验 (请简要概况)." << endl;
}
};
int main()
{
Resume* r1 = new ResumeA;
r1->FillResume();
Resume* r2 = new ResumeB;
r2->FillResume();
delete r1;
delete r2;
system("pause");
return 0;
}
命令模式
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Chef
{
public:
void makeMeals()
{
cout << "正在做饭中..." << endl;
}
void cancelMeals()
{
cout << "已取消做饭!" << endl;
}
void makeNoodles()
{
cout << "正在煮面中..." << endl;
}
void cancelNoodles()
{
cout << "已取消煮面!" << endl;
}
};
class Command
{
protected:
Chef* chef;
public:
virtual void executeCommand() = 0;
virtual void cancelCommand() = 0;
virtual ~Command() {};
};
class AboutMealsCommand : Command
{
public:
AboutMealsCommand(Chef* c)
{
this->chef = c;
}
void executeCommand()
{
chef->makeMeals();
}
void cancelCommand()
{
chef->cancelMeals();
}
};
class AboutNoodlesCommand : Command
{
public:
AboutNoodlesCommand(Chef* c)
{
this->chef = c;
}
void executeCommand()
{
chef->makeNoodles();
}
void cancelCommand()
{
chef->cancelNoodles();
}
};
class Customer
{
private:
vector<Command*> commandQueue;
public:
void add(Command* command)
{
commandQueue.push_back(command);
cout << "客人发出了一条命令" << endl;
}
void remove(Command* command)
{
for (auto iter = commandQueue.begin(); iter != commandQueue.end(); iter++)
{
if ((*iter) == command)
{
commandQueue.erase(iter);
break;
}
}
cout << "客人取消了一条命令" << endl;
}
void confirm()
{
for (auto command : commandQueue)
{
command->executeCommand();
}
commandQueue.clear();
}
void cancel()
{
for (auto command : commandQueue)
{
command->cancelCommand();
}
commandQueue.clear();
}
};
int main()
{
Chef* chef = new Chef();
Command* mealsCommand = (Command*) new AboutMealsCommand(chef);
Command* noodlesCommand = (Command*) new AboutNoodlesCommand(chef);
Customer* customer = new Customer();
customer->add(mealsCommand);
customer->add(noodlesCommand);
customer->remove(mealsCommand);
customer->confirm();
customer->add(noodlesCommand);
customer->cancel();
delete customer;
delete chef;
delete mealsCommand;
delete noodlesCommand;
system("pause");
return 0;
}
责任链模式
#include<iostream>
#include<string>
using namespace std;
class Handler
{
protected:
Handler* nextHanler;
public:
Handler() : nextHanler(nullptr) { cout << "初始化成功!" << endl; }
void setNextHandler(Handler* next)
{
this->nextHanler = next;
}
virtual void handleRequest(int days) = 0;
virtual ~Handler() {};
};
class GroupLeader : public Handler
{
public:
void handleRequest(int days)
{
cout << "组长回复:";
if (days <= 1)
{
cout << "同意请假!" << endl;
}
else
{
cout << "请假太久了,你去找经理请假。" << endl;
if (this->nextHanler != nullptr) nextHanler->handleRequest(days);
}
}
};
class Manager : public Handler
{
public:
void handleRequest(int days)
{
cout << "经理回复:";
if (days <= 3)
{
cout << "同意请假!" << endl;
}
else
{
cout << "请假太久了,你去找老板请假。" << endl;
if (this->nextHanler != nullptr) nextHanler->handleRequest(days);
}
}
};
class Boss : public Handler
{
public:
void handleRequest(int days)
{
cout << "老板回复:";
if (days <= 7)
{
cout << "同意请假!" << endl;
}
else
{
cout << "请假太久了,不行!" << endl;
if (this->nextHanler != nullptr) nextHanler->handleRequest(days);
}
}
};
int main()
{
Handler* groupLeader = new GroupLeader;
Handler* manager = new Manager;
Handler* boss = new Boss;
groupLeader->setNextHandler(manager);
manager->setNextHandler(boss);
int days;
days = 1;
cout << "想要请假" << days << "天" << endl;
groupLeader->handleRequest(days);
days = 3;
cout << "想要请假" << days << "天" << endl;
groupLeader->handleRequest(days);
days = 7;
cout << "想要请假" << days << "天" << endl;
groupLeader->handleRequest(days);
days = 30;
cout << "想要请假" << days << "天" << endl;
groupLeader->handleRequest(days);
delete groupLeader;
delete manager;
delete boss;
system("pause");
return 0;
}
策略模式
#include<iostream>
#include<string>
using namespace std;
class Strategy
{
public:
virtual int execute(int left, int right) = 0;
};
class Add : public Strategy
{
public:
int execute(int left, int right)
{
return left + right;
}
};
class Sub : public Strategy
{
public:
int execute(int left, int right)
{
return left - right;
}
};
class Mul : public Strategy
{
public:
int execute(int left, int right)
{
return left * right;
}
};
class Div : public Strategy
{
public:
int execute(int left, int right)
{
if (right == 0)
{
cout << "除数不能为零!" << endl;
return 0;
}
return left / right;
}
};
class Container
{
private:
Strategy* strategy;
public:
void setStrategy(Strategy* s)
{
this->strategy = s;
}
int executeStrategy(int left, int right)
{
return strategy->execute(left, right);
}
};
int main()
{
Container* container = new Container;
int left, right;
char symbol;
Strategy* strategy = nullptr;
while (true)
{
cout << "(Count) >>> ";
cin >> left >> symbol >> right;
switch (symbol)
{
case '+':
strategy = new Add;
container->setStrategy(strategy);
break;
case '-':
strategy = new Sub;
container->setStrategy(strategy);
break;
case '*':
strategy = new Mul;
container->setStrategy(strategy);
break;
case '/':
strategy = new Div;
container->setStrategy(strategy);
break;
}
cout << container->executeStrategy(left, right) << endl;
delete strategy;
}
system("pause");
return 0;
}
观察者模式
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Boss;
class Employee
{
private:
string m_name;
public:
Employee(string name) : m_name(name) {};
void updateInfomation(string info)
{
cout << m_name << "收到情报:" << info << endl;
if (info == "老板来了")
{
cout << "--> 开启工作模式" << endl;
}
else if (info == "老板走了")
{
cout << "--> 开启摸鱼模式" << endl;
}
}
};
class Boss
{
private:
string information;
vector<Employee*> employeeContainer;
public:
void addEmployee(Employee* employee)
{
this->employeeContainer.push_back(employee);
}
void setActionInfo(string info)
{
this->information = info;
notify();
}
void notify()
{
for (auto v : employeeContainer)
{
v->updateInfomation(this->information);
}
}
};
int main()
{
Boss* boss = new Boss;
Employee* emp1 = new Employee("小明");
Employee* emp2 = new Employee("老张");
Employee* emp3 = new Employee("老李");
boss->addEmployee(emp1);
boss->addEmployee(emp2);
boss->addEmployee(emp3);
boss->setActionInfo("老板来了");
boss->setActionInfo("老板走了");
delete boss;
delete emp1;
delete emp2;
delete emp3;
system("pause");
return 0;
}
访问者模式
#include<iostream>
#include<string>
using namespace std;
class Place;
class Visitor
{
public:
virtual void visitHospital(Place* place) = 0;
virtual void visitResteraunt(Place* place) = 0;
virtual ~Visitor() {};
};
class Place
{
protected:
string placeName;
public:
string getName()
{
return this->placeName;
}
virtual void accept(Visitor* visitor) = 0;
virtual ~Place() {}
};
class Hospital : public Place
{
public:
Hospital(string name)
{
this->placeName = name;
}
void accept(Visitor* visitor)
{
visitor->visitHospital(this);
}
};
class Resteraunt : public Place
{
public:
Resteraunt(string name)
{
this->placeName = name;
}
void accept(Visitor* visitor)
{
visitor->visitResteraunt(this);
}
};
class Doctor : public Visitor
{
public:
void visitHospital(Place* place)
{
cout << "医生访问" << place->getName() << "是为了治疗病人" << endl;
}
void visitResteraunt(Place* place)
{
cout << "医生访问" << place->getName() << "是为了吃一顿饭" << endl;
}
};
class Chef : public Visitor
{
public:
void visitHospital(Place* place)
{
cout << "厨师访问" << place->getName() << "是为了治病" << endl;
}
void visitResteraunt(Place* place)
{
cout << "厨师访问" << place->getName() << "是为了做菜" << endl;
}
};
int main()
{
Place* hospital = new Hospital("丽江市第一人名医院");
Place* resteraunt = new Resteraunt("幸福餐馆");
Visitor* doctor = new Doctor();
Visitor* chef = new Chef();
hospital->accept(doctor);
resteraunt->accept(doctor);
hospital->accept(chef);
resteraunt->accept(chef);
delete hospital;
delete resteraunt;
delete doctor;
delete chef;
system("pause");
return 0;
}
中介者模式
#include<iostream>
#include<string>
using namespace std;
class Role;
class Mediator
{
protected:
Role* hr;
Role* student;
public:
void set_HR(Role* hr)
{
this->hr = hr;
}
void set_Student(Role* student)
{
this->student = student;
}
virtual void match() = 0;
};
class Role
{
protected:
string name;
string offer;
Mediator* mediator;
public:
string getName()
{
return this->name;
}
string getOffer()
{
return this->offer;
}
virtual void match(Role* role) = 0;
};
class Student : public Role
{
public:
Student(string name, string offer, Mediator* mediator)
{
this->name = name;
this->offer = offer;
this->mediator = mediator;
}
void match(Role* role)
{
mediator->set_HR(role);
mediator->set_Student(this);
mediator->match();
}
};
class HR : public Role
{
public:
HR(string name, string offer, Mediator* mediator)
{
this->name = name;
this->offer = offer;
this->mediator = mediator;
}
void match(Role* role)
{
mediator->set_HR(this);
mediator->set_Student(role);
mediator->match();
}
};
class LiepinApp : public Mediator
{
public:
void match()
{
cout << "------------------" << endl;
cout << hr->getName() << "提供岗位:" << hr->getOffer() << endl;
cout << student->getName() << "需求职位:" << student->getOffer() << endl;
if (hr->getOffer() == student->getOffer())
{
cout << "配对成功!" << endl;
}
else
{
cout << "配对失败!" << endl;
}
cout << "------------------" << endl;
}
};
int main()
{
Mediator* app1 = new LiepinApp;
Role* hr = new HR("花儿姐", "软件工程师", app1);
app1->set_HR(hr);
Role* student = new Student("小明", "机械工程师", app1);
app1->set_Student(student);
app1->match();
delete app1;
delete hr;
delete student;
system("pause");
return 0;
}
备忘录模式
#include<iostream>
#include<string>
using namespace std;
class Memorandum
{
private:
int blood;
int attack;
int defense;
public:
Memorandum(int blood, int attack, int defense)
{
this->blood;
this->attack;
this->defense;
}
int getBlood() { return this->blood; }
int getAttack() { return this->attack; }
int getDefense() { return this->defense; }
};
class GameRole
{
private:
int blood;
int attack;
int defense;
public:
GameRole()
{
this->blood = 100;
this->attack = 100;
this->defense = 100;
}
void showState()
{
cout << "当前角色:"
<< "[生命力:" << this->blood
<< "] [攻击力:" << this->attack
<< "] [防御力:" << this->defense << "]" << endl;
}
void fight()
{
this->blood -= 40;
this->attack -= 16;
this->defense -= 32;
cout << "遭受敌人攻击!生命力-40,攻击力-16,防御力-32..." << endl;
if (blood <= 0)
{
cout << "您已阵亡" << endl;
}
}
Memorandum* saveState()
{
cout << "存档成功!" << endl;
return new Memorandum(this->blood, this->attack, this->defense);
}
void recoveryState(Memorandum* m)
{
this->blood = m->getBlood();
this->attack = m->getAttack();
this->defense = m->getDefense();
cout << "恢复存档成功!" << endl;
}
};
int main()
{
GameRole* role = new GameRole();
role->showState();
role->fight();
Memorandum* record = role->saveState();
role->fight();
role->fight();
role->recoveryState(record);
role->fight();
delete role;
delete record;
system("pause");
return 0;
}
状态模式
#include<iostream>
#include<string>
#include<memory>
using namespace std;
class Context;
class AbstractState
{
public:
virtual void handle(Context* p) = 0;
};
class NoneState : public AbstractState
{
void handle(Context* p)
{
cout << "没有上下文...";
}
};
class ExistState : public AbstractState
{
void handle(Context* p)
{
cout << "存在上下文...";
}
};
class Context
{
private:
AbstractState* state;
public:
Context(AbstractState* state) : state(state) {}
void request()
{
cout << "内容:{";
if (state)
{
state->handle(this);
}
cout << "}" << endl;
}
void changeState(AbstractState* newState)
{
state = newState;
}
};
int main()
{
unique_ptr<AbstractState> noneState = make_unique<NoneState>();
unique_ptr<AbstractState> existState = make_unique<ExistState>();
unique_ptr<Context> context = make_unique<Context>(nullptr);
context->request();
context->changeState(noneState.get());
context->request();
context->changeState(existState.get());
context->request();
system("pause");
return 0;
}
迭代器模式
#include<iostream>
#include<string>
#include<memory>
#include<vector>
using namespace std;
template<class U>
class Iterator;
template<class T>
class SimpleVector
{
friend class Iterator<T>;
protected:
vector<T> vector;
public:
void add(T data)
{
this->vector.push_back(data);
}
void remove()
{
this->vector.pop_back();
}
unique_ptr<Iterator<T>> createIterator()
{
return make_unique<Iterator<T>>(this);
}
};
template<class T>
class Iterator
{
protected:
SimpleVector<T>* container;
typedef typename vector<T>::iterator iter_type;
iter_type iter;
public:
Iterator(SimpleVector<T>* simpleVector)
{
this->container = simpleVector;
this->iter = simpleVector->vector.begin();
}
T get()
{
return *(this->iter);
}
void next()
{
this->iter++;
}
bool reachTheEnd()
{
return (this->iter == this->container->vector.end());
}
};
int main()
{
SimpleVector<int> v;
for (int i = 1; i < 10; i++)
{
v.add(i * 100);
}
unique_ptr<Iterator<int>> iterator = v.createIterator();
while (!iterator->reachTheEnd())
{
cout << iterator->get() << endl;
iterator->next();
}
system("pause");
return 0;
}
解释器模式
#include<iostream>
#include<string>
#include<map>
#include<stack>
using namespace std;
class Interpreter
{
public:
virtual int parse(map<string, int>& var) = 0;
};
class VarInterpreter : public Interpreter
{
private:
string key;
public:
VarInterpreter(string key) : key(key) {};
int parse(map<string, int>& var)
{
return var[key];
}
};
class SymbolInterpreter : public Interpreter
{
protected:
Interpreter* left;
Interpreter* right;
public:
SymbolInterpreter(Interpreter* left, Interpreter* right) : left(left), right(right) {};
Interpreter* getLeft() { return left; }
Interpreter* getRight() { return right; }
};
class AddInterpreter : SymbolInterpreter
{
public:
AddInterpreter(Interpreter* left, Interpreter* right) : SymbolInterpreter(left, right) {};
int parse(map<string, int>& var)
{
int res = left->parse(var) + right->parse(var);
return res;
}
};
class SubInterpreter : public SymbolInterpreter
{
public:
SubInterpreter(Interpreter* left, Interpreter* right) : SymbolInterpreter(left, right) {};
int parse(map<string, int>& var)
{
int res = left->parse(var) - right->parse(var);
return res;
}
};
class Parser
{
private:
Interpreter* finalInterpreter;
stack<Interpreter*> stk;
public:
Parser(string str)
{
Interpreter* left = nullptr;
Interpreter* right = nullptr;
this->finalInterpreter = nullptr;
for (int i = 0; i < str.length(); i++)
{
switch (str[i])
{
case '@':
left = stk.top();
right = new VarInterpreter(str.substr(++i, 1));
stk.push(right);
stk.push((Interpreter*) new AddInterpreter(left, right));
break;
case '#':
left = stk.top();
right = new VarInterpreter(str.substr(++i, 1));
stk.push(right);
stk.push((Interpreter*) new SubInterpreter(left, right));
break;
default:
stk.push(new VarInterpreter(str.substr(i, 1)));
break;
}
}
if (!stk.empty())
{
this->finalInterpreter = stk.top();
}
}
int run(map<string, int>& var)
{
int res = (this->finalInterpreter == nullptr) ? -1: finalInterpreter->parse(var);
while (!stk.empty())
{
delete stk.top();
stk.pop();
}
return res;
}
};
int main()
{
string str = "a@b#c";
map<string, int> var = {
{"a", 30},
{"b", 20},
{"c", 25}
};
Parser p(str);
cout << p.run(var) << endl;
system("pause");
return 0;
}