1.观察者模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
using namespace std;
class View;
class DataModel
{
public:
virtual ~DataModel() {};
virtual void add(View *pView) = 0;
virtual void remove(View *pView) = 0;
virtual void notify() = 0;
};
class View
{
public:
virtual ~View()
{
printf("~View()\n");
}
virtual void update() = 0;
};
class IntModel : public DataModel
{
public:
~IntModel()
{
clear();
}
void add(View* pView)
{
auto iter = std::find(m_list.begin(), m_list.end(), pView);
if (iter == m_list.end())
{
m_list.push_back(pView);
}
}
void remove(View *pView)
{
for (auto &it : m_list)
{
if (pView == it)
{
delete it;
it = nullptr;
}
}
}
void notify()
{
auto iter = m_list.begin();
for (; iter != m_list.end(); iter++)
{
(*iter)->update();
}
}
private:
void clear()
{
if (!m_list.empty())
{
for (auto &it : m_list)
{
delete it;
it = nullptr;
}
}
}
private:
std::list<View*> m_list;
};
class TreeView : public View
{
public:
TreeView(string name) : m_name(name), View()
{
}
~TreeView()
{
printf("~TreeView()\n");
}
void update()
{
printf("%s : Update\n", m_name.data());
}
private:
string m_name;
};
void main()
{
View *pV1 = new TreeView("v1");
View *pV2 = new TreeView("v2");
DataModel* pModel = new IntModel;
pModel->add(pV1);
pModel->add(pV2);
pModel->notify();
//pModel->remove(pV1);
//pModel->notify();
delete pModel;
}
2.职责链模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
using namespace std;
enum RequestLevel
{
One = 1,
Two,
Three
};
class Leader
{
public:
Leader(Leader* pLeader) : m_pLeader(pLeader) {}
virtual ~Leader(){}
virtual void handleRequest(RequestLevel level) = 0;
public:
Leader* m_pLeader;
};
class Monitor : public Leader
{
public:
Monitor(Leader *leader) : Leader(leader) {}
void handleRequest(RequestLevel level)
{
if (level < Two)
{
cout << "Monitor handle request:" << level << endl;
}
else
{
m_pLeader->handleRequest(level);
}
}
};
class Captain : public Leader
{
public:
Captain(Leader* pLeader) : Leader(pLeader){}
void handleRequest(RequestLevel level)
{
if (level < Three)
{
cout << "Captain handle request:" << level << endl;
}
else
{
m_pLeader->handleRequest(level);
}
}
};
class General : public Leader
{
public:
General(Leader *pLeader) : Leader(pLeader){}
void handleRequest(RequestLevel level)
{
cout << "General handle request :" << level << endl;
}
};
void main()
{
Leader *general = new General(nullptr);
Leader *captain = new General(general);
Leader *monitor = new Monitor(captain);
monitor->handleRequest(Three);
}
三.中介者模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
using namespace std;
class Mediator;
class Person
{
public:
virtual ~Person(){}
virtual void setMediator(Mediator *mediator)
{
m_mediator = mediator;
}
virtual void sendMessage(const string& message) = 0;
virtual void getMessage(const string& message) = 0;
protected:
Mediator* m_mediator;
};
class Mediator
{
public:
virtual ~Mediator(){}
virtual void setBuyer(Person *buyer) = 0;
virtual void setSeller(Person *seller) = 0;
virtual void send(const string& message, Person *person) = 0;
};
class Buyer : public Person
{
public:
void sendMessage(const string& message) override
{
m_mediator->send(message, this);
}
void getMessage(const string& message) override
{
cout << "Buyer Get:" << message.data() << endl;
}
};
class Seller : public Person
{
public:
void sendMessage(const string& message) override
{
m_mediator->send(message, this);
}
void getMessage(const string& message) override
{
cout << "Seller Get:" << message.data() << endl;
}
};
class HouseMediator : public Mediator
{
public:
HouseMediator() : m_buyer(nullptr), m_seller(nullptr) {}
void setBuyer(Person *buyer) override
{
m_buyer = buyer;
}
void setSeller(Person *seller) override
{
m_seller = seller;
}
void send(const string& message, Person *person) override
{
if (person == m_buyer)
{
m_buyer->getMessage(message);
}
else if (person == m_seller)
{
m_seller->getMessage(message);
}
}
private:
Person* m_buyer;
Person* m_seller;
};
void main()
{
Person *buyer = new Buyer;
Person *seller = new Seller;
Mediator *houseMediator = new HouseMediator;
buyer->setMediator(houseMediator);
seller->setMediator(houseMediator);
houseMediator->setBuyer(buyer);
houseMediator->setSeller(seller);
buyer->sendMessage("1.5?");
seller->sendMessage("2!!!");
}
四.备忘录模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
using namespace std;
typedef struct
{
int grade;
string arm;
string corps;
}GameValue;
class Memento
{
public:
Memento() {};
Memento(GameValue value) : m_gameValue(value) {};
GameValue getValue()
{
return m_gameValue;
}
private:
GameValue m_gameValue;
};
class Caretake
{
public:
void save(Memento memento)
{
m_memento = memento;
}
Memento load()
{
return m_memento;
}
private:
Memento m_memento;
};
class Game
{
public:
Game(GameValue value) : m_gameValue(value){}
void addGrade()
{
m_gameValue.grade++;
}
void replaceArm(string arm)
{
m_gameValue.arm = arm;
}
void replaceCorps(string corps)
{
m_gameValue.corps = corps;
}
Memento saveValue()
{
Memento memento(m_gameValue);
return memento;
}
void load(Memento memento)
{
m_gameValue = memento.getValue();
}
void showValue()
{
cout << "Grade:" << m_gameValue.grade << endl;
cout << "Arm:" << m_gameValue.arm.data() << endl;
cout << "Corps:" << m_gameValue.corps.data() << endl;
}
private:
GameValue m_gameValue;
};
void main()
{
GameValue v1 = { 0, "AK", "3K" };
Game game(v1);
game.addGrade();
game.showValue();
cout << "................" << endl;
Caretake care;
care.save(game.saveValue());
game.addGrade();
game.replaceArm("M16");
game.replaceCorps("123");
game.showValue();
cout << "..............." << endl;
game.load(care.load());
game.showValue();
}
五.装饰者模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
using namespace std;
class Dumplings
{
public:
virtual ~Dumplings() {};
virtual void showDressing() = 0;
};
class MeatDumplings : public Dumplings
{
public:
~MeatDumplings()
{
cout << "~MeatDumplings()" << endl;
}
void showDressing()
{
cout << "Add Meat" << endl;
}
};
class DecorateDumpling : public Dumplings
{
public:
DecorateDumpling(Dumplings *d) : m_dumpling(d){}
virtual ~DecorateDumpling()
{
cout << "~DecorateDumplings()" << endl;
}
void showDressing()
{
m_dumpling->showDressing();
}
private:
Dumplings *m_dumpling;
};
class SaltDecorate : public DecorateDumpling
{
public:
SaltDecorate(Dumplings* d) : DecorateDumpling(d){}
~SaltDecorate()
{
cout << "~SaltDecorate()" << endl;
}
void showDressing() override
{
DecorateDumpling::showDressing();
addDressing();
}
private:
void addDressing()
{
cout << "Add Salt" << endl;
}
};
class OilDecorate : public DecorateDumpling
{
public:
OilDecorate(Dumplings *d) : DecorateDumpling(d) {}
~OilDecorate() { cout << "~OilDecorate()" << endl; }
void showDressing()
{
DecorateDumpling::showDressing();
addDressing();
}
private:
void addDressing()
{
cout << "Add Oil" << endl;
}
};
class CabbageDecorator : public DecorateDumpling
{
public:
CabbageDecorator(Dumplings *d) : DecorateDumpling(d){}
~CabbageDecorator()
{
cout << "~CabbageDecorator()" << endl;
}
void showDressing()
{
DecorateDumpling::showDressing();
addDressing();
}
private:
void addDressing()
{
cout << "Add Cabbage() " << endl;
}
};
void main()
{
Dumplings *d = new MeatDumplings;
Dumplings *d1 = new SaltDecorate(d);
Dumplings *d2 = new OilDecorate(d1);
Dumplings *d3 = new CabbageDecorator(d2);
d3->showDressing();
delete d;
delete d1;
delete d2;
delete d3;
}
六.桥接模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
using namespace std;
class App
{
public:
virtual ~App() { cout << "~App" << endl;}
virtual void run() = 0;
};
class GameApp : public App
{
public:
void run()
{
cout << "GameApp Running" << endl;
}
};
class TranslateApp : public App
{
public:
void run()
{
cout << "TranslateApp Runnings" << endl;
}
};
class MobilePhone
{
public:
virtual ~MobilePhone() { cout << "~MobilePhone" << endl; }
virtual void appRun(App* app) = 0;
};
class XiaoMi : public MobilePhone
{
public:
void appRun(App *app)
{
cout << "XiaoMi:";
app->run();
}
};
class Huawei : public MobilePhone
{
public:
void appRun(App *app)
{
cout << "HuaWei;";
app->run();
}
};
void main()
{
App *gameApp = new GameApp;
App *translateApp = new TranslateApp;
MobilePhone *mi = new XiaoMi;
MobilePhone *hua = new Huawei;
mi->appRun(gameApp);
mi->appRun(translateApp);
hua->appRun(gameApp);
hua->appRun(translateApp);
delete hua;
delete mi;
delete gameApp;
delete translateApp;
}
七.享元模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
enum MoneyCategory
{
Coin,
bankNote
};
enum FaceValue
{
valueOne = 1,
valueTwo
};
class Money
{
public:
Money(MoneyCategory cate) : m_mCate(cate){}
virtual ~Money() { cout << "~Money()" << endl; }
virtual void save() = 0;
private:
MoneyCategory m_mCate;
};
class MoneyCoin : public Money
{
public:
MoneyCoin(MoneyCategory cate) : Money(cate){}
~MoneyCoin() { cout << "~Money()" << endl; }
void save()
{
cout << "Save Coin" << endl;
}
};
class MoneyNote : public Money
{
public:
MoneyNote(MoneyCategory cate) : Money(cate){}
~MoneyNote() { cout << "~MoneyNote()" << endl; }
void save()
{
cout << "Save BankNote" << endl;
}
};
class Bank
{
public:
Bank() : m_coin(nullptr), m_note(nullptr), m_count(0){};
~Bank()
{
if (m_coin != nullptr)
{
delete m_coin;
m_coin = nullptr;
}
if (m_note != nullptr)
{
delete m_note;
m_note = nullptr;
}
}
void saveMoney(MoneyCategory cate, FaceValue value)
{
switch (cate)
{
case Coin:
{
if (m_coin == nullptr)
{
m_coin = new MoneyCoin(Coin);
}
m_coin->save();
m_vecValue.push_back(value);
break;
}
case bankNote:
{
if (m_note == nullptr)
{
m_note = new MoneyNote(bankNote);
}
m_note->save();
m_vecValue.push_back(value);
break;
}
default:
break;
}
}
int sumValue()
{
auto iter = m_vecValue.begin();
for (; iter != m_vecValue.end(); iter++)
{
m_count += *iter;
}
return m_count;
}
private:
vector<FaceValue> m_vecValue;
Money *m_coin;
Money *m_note;
int m_count;
};
void main()
{
Bank b1;
b1.saveMoney(Coin, valueOne);
b1.saveMoney(Coin, valueOne);
b1.saveMoney(Coin, valueTwo);
b1.saveMoney(bankNote, valueOne);
b1.saveMoney(bankNote, valueTwo);
cout << b1.sumValue() << endl;
}
八.代理模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Girl
{
public:
Girl(string name = "girl") : m_string(name) {}
string getNmae()
{
return m_string;
}
private:
string m_string;
};
class Profession
{
public:
virtual ~Profession(){}
virtual void profess() = 0;
};
class YongMan : Profession
{
public:
YongMan(Girl girl) : m_girl(girl){}
void profess()
{
cout << "Yong man love" << m_girl.getNmae().data() << endl;
}
private:
Girl m_girl;
};
class ManProxy : public Profession
{
public:
ManProxy(Girl girl) : m_man(new YongMan(girl)){}
void profess()
{
cout << "I am Proxy" << endl;
m_man->profess();
}
private:
YongMan *m_man;
};
void main()
{
Girl girl("hei");
Profession *proxy = new ManProxy(girl);
proxy->profess();
delete proxy;
}
九.组合模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <list>
#include <iostream>
using namespace std;
class Company
{
public:
Company(string name) : m_name(name){}
virtual ~Company() {};
virtual void add(Company* company) = 0;
virtual void remove(string name) = 0;
virtual void display(int depth) = 0;
string getName()
{
return m_name;
}
protected:
string m_name;
};
class ConcretCompany : public Company
{
public:
ConcretCompany(string name) : Company(name){}
~ConcretCompany()
{
cout << "~ConcreteCompany()" << endl;
}
void add(Company *company) override;
void remove(string name) override;
void display(int depth) override;
private:
list<shared_ptr<Company>> m_listCompany;
};
void ConcretCompany::add(Company *company)
{
shared_ptr<Company> temp(company);
m_listCompany.push_back(temp);
}
void ConcretCompany::remove(string name)
{
string strName;
for (auto company : m_listCompany)
{
strName = company.get()->getName();
if (strName == name)
{
m_listCompany.remove(company);
}
}
}
void ConcretCompany::display(int depth)
{
for (int i = 0; i < depth; i++)
{
cout << "-";
}
cout << m_name.data() << endl;
for (auto &company : m_listCompany)
{
company.get()->display(depth + 2);
}
}
//公司下的部门
class FinanceDept :public Company //树叶
{
public:
FinanceDept(string name) :Company(name)
{}
~FinanceDept()
{
cout << "~FinanceDept()" << endl;
}
void add(Company* company) override;
void remove(string name) override;
void display(int depth) override;
};
void FinanceDept::add(Company* company)
{
cout << "FinanceDept add failed" << endl;
}
void FinanceDept::remove(string name)
{
cout << "FinanceDept remove failed" << endl;
}
void FinanceDept::display(int depth)
{
for (int i = 0; i < depth; i++)
{
cout << "-";
}
cout << m_name.data() << endl;
}
//公司下的部门
class HRDept :public Company //树叶
{
public:
HRDept(string name) :Company(name)
{}
~HRDept()
{
cout << "~HRDept()" << endl;
}
void add(Company* company) override;
void remove(string name) override;
void display(int depth) override;
};
void HRDept::add(Company* company)
{
cout << "HRDept add failed" << endl;
}
void HRDept::remove(string name)
{
cout << "HRDept remove failed" << endl;
}
void HRDept::display(int depth)
{
for (int i = 0; i < depth; i++)
{
cout << "-";
}
cout << m_name.data() << endl;
}
int main(int argc, char *argv[])
{
Company* root = new ConcretCompany("zong");
Company* f1 = new FinanceDept("F1");
Company* h1 = new HRDept("H1");
root->add(f1);
root->add(h1);
Company* c1 = new ConcretCompany("fen1");
Company* f2 = new FinanceDept("F2");
Company* h2 = new HRDept("H2");
c1->add(f2);
c1->add(h2);
root->add(c1);
root->display(0);
delete root;
return 0;
}
9.外观模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <list>
#include <iostream>
using namespace std;
class Cpu
{
public:
void productCpu()
{
cout << "Product Cpu" << endl;
}
};
class Ram
{
public:
void productRam()
{
cout << "Product Ram" << endl;
}
};
class Graphics
{
public:
void productGraphics()
{
cout << "Product Graphics" << endl;
}
};
class Computer
{
public:
void productComputer()
{
Cpu cpu;
cpu.productCpu();
Ram ram;
ram.productRam();
Graphics graphics;
graphics.productGraphics();
}
};
int main()
{
Computer computer;
computer.productComputer();
return 0;
}
十.建造者模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <memory>
using namespace std;
typedef enum
{
type1,
type2
}ProductType;
class Product
{
public:
void setNum(int num);
void setColor(string color);
void setType(ProductType type);
void showProduct();
private:
int m_num;
string m_color;
ProductType m_type;
};
void Product::setNum(int num)
{
m_num = num;
}
void Product::setColor(string color)
{
m_color = color;
}
void Product::setType(ProductType type)
{
m_type = type;
}
void Product::showProduct()
{
cout << "Product" << endl;
cout << "-----num:" << m_num << endl;
cout << "-----color:" << m_color.data() << endl;
cout << "-----type:" << m_type << endl;
}
class Builder
{
public:
Builder(){}
virtual ~Builder(){}
virtual void buildNum(int num) = 0;
virtual void buildColor(string color) = 0;
virtual void buildType(ProductType type) = 0;
virtual void creatProduct() = 0;
virtual Product* getProduct() = 0;
virtual void show() = 0;
};
class BuilderA : public Builder
{
public:
BuilderA() {}
virtual ~BuilderA() {}
virtual void buildNum(int num) override;
virtual void buildColor(string color) override;
virtual void buildType(ProductType type) override;
virtual void creatProduct() override;
virtual Product* getProduct() override;
virtual void show() override;
private:
Product *m_product;
};
void BuilderA::buildNum(int num)
{
cout << "BuilderA build Num" << num << endl;
m_product->setNum(num);
}
void BuilderA::buildColor(string color)
{
cout << "BuilderA build Color" << color.data() << endl;
m_product->setColor(color);
}
void BuilderA::buildType(ProductType type)
{
cout << "BuilderA build Type" << type << endl;
m_product->setType(type);
}
void BuilderA::creatProduct()
{
cout << "BuilderA CreatProduct:" << endl;
m_product = new Product;
}
Product* BuilderA::getProduct()
{
return m_product;
}
void BuilderA::show()
{
m_product->showProduct();
}
class BuilderB : public Builder
{
public:
BuilderB() {}
virtual ~BuilderB() {}
virtual void buildNum(int num) override;
virtual void buildColor(string color) override;
virtual void buildType(ProductType type) override;
virtual void creatProduct() override;
virtual Product* getProduct() override;
virtual void show() override;
private:
Product *m_product;
};
void BuilderB::buildNum(int num)
{
cout << "BuilderA build Num" << num << endl;
m_product->setNum(num);
}
void BuilderB::buildColor(string color)
{
cout << "BuilderA build Color" << color.data() << endl;
m_product->setColor(color);
}
void BuilderB::buildType(ProductType type)
{
cout << "BuilderA build Type" << type << endl;
m_product->setType(type);
}
void BuilderB::creatProduct()
{
cout << "BuilderA CreatProduct:" << endl;
m_product = new Product;
}
Product* BuilderB::getProduct()
{
return m_product;
}
void BuilderB::show()
{
m_product->showProduct();
}
class Director
{
public:
Director(Builder* builder) : m_builder(builder)
{
}
void setBuilder(Builder* builder)
{
m_builder = builder;
}
void construct(int num, string color, ProductType type)
{
m_builder->creatProduct();
m_builder->buildNum(num);
m_builder->buildColor(color);
m_builder->buildType(type);
}
private:
Builder *m_builder;
};
int main()
{
Builder *builderA = new BuilderA;
Builder *builderB = new BuilderB;
Director direct(builderA);
direct.construct(14, "blue", type1);
direct.setBuilder(builderB);
direct.construct(15, "red", type2);
delete builderA;
delete builderB;
return 0;
}
十一.模板方法模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <memory>
using namespace std;
class Computer
{
public:
void product()
{
installCpu();
installRam();
installCard();
}
protected:
virtual void installCpu() = 0;
virtual void installRam() = 0;
virtual void installCard() = 0;
};
class ComputerA : public Computer
{
protected:
void installCpu() override
{
cout << "ComputerA install inter Core i5" << endl;
}
void installRam() override
{
cout << "ComputerA install 2G Ram" << endl;
}
void installCard() override
{
cout << "ComputerA install Gtx940" << endl;
}
};
class ComputerB : public Computer
{
protected:
void installCpu() override
{
cout << "ComputerB install inter Core i7" << endl;
}
void installRam() override
{
cout << "ComputerB install 4G Ram" << endl;
}
void installCard() override
{
cout << "ComputerB install Gtx990" << endl;
}
};
int main()
{
Computer *computerA = new ComputerA;
Computer *computerB = new ComputerB;
computerA->product();
computerB->product();
delete computerA;
delete computerB;
return 0;
}
十二.原型模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <memory>
using namespace std;
class Clone
{
public:
Clone() {};
virtual ~Clone() {};
virtual Clone *clone() = 0;
virtual void show() = 0;
};
class Sheep : public Clone
{
public:
Sheep(int id, string name) :m_id(id), m_name(name)
{
cout << "Sheep() id add:" << &m_id << endl;
cout << "Sheep() name add:" << &m_name << endl;
}
~Sheep() {};
Sheep(const Sheep& obj)
{
this->m_id = obj.m_id;
this->m_name = obj.m_name;
cout << "Sheep(const Sheep& obj) id add:" << &m_id << endl;
cout << "Sheep(const Sheep& obj) name add:" << &m_name << endl;
}
Clone *clone()
{
return new Sheep(*this);
}
void show()
{
cout << "id:" << m_id << endl;
cout << "name:" << m_name.data() << endl;
}
private:
int m_id;
string m_name;
};
int main()
{
Clone* s1 = new Sheep(1, "abs");
s1->show();
Clone* s2 = s1->clone();
s2->show();
delete s1;
delete s2;
return 0;
}
十三.单例模式-懒汉模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <memory>
#include <mutex>
using namespace std;
//懒汉式
mutex mtx;
class Singleton
{
public:
static Singleton* getInstance();
~Singleton() {};
private:
static Singleton *m_pSingleton;
Singleton() {};
Singleton(const Singleton& obj) = delete;
Singleton& operator=(const Singleton& obj) = delete;
};
Singleton *Singleton::m_pSingleton = NULL;
Singleton *Singleton::getInstance()
{
if (m_pSingleton == NULL)
{
mtx.lock();
m_pSingleton = new Singleton;
mtx.unlock();
}
return m_pSingleton;
}
十四. 单例模式-饿汉模式
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <memory>
#include <mutex>
using namespace std;
//饿汉式(线程安全)
class Singleton
{
public:
static Singleton* getInstance();
~Singleton() {};
private:
static Singleton *m_pSingleton;
Singleton() {};
Singleton(const Singleton& obj) = delete;
Singleton& operator=(const Singleton& obj) = delete;
};
Singleton *Singleton::m_pSingleton = new Singleton();
Singleton *Singleton::getInstance()
{
return m_pSingleton;
}
十五.适配器模式