1.策略模式
例子来自《设计模式之禅》
#include <iostream>
using namespace std;
class Strategy
{
public:
virtual void dosomething()=0;
};
class ConcreteStrategy_first:public Strategy
{
public:
void dosomething()
{
cout<<"找乔国老开后门"<<endl;
}
};
class ConcreteStrategy_second:public Strategy
{
public:
void dosomething()
{
cout<<"吴国太开绿灯"<<endl;
}
};
class ConcreteStrategy_third:public Strategy
{
public:
void dosomething()
{
cout<<"孙夫人断后"<<endl;
}
};
class Context
{
private:
Strategy* strategy;
public:
Context(Strategy* strategy)
{
this->strategy=strategy;
}
void open_text()
{
this->strategy->dosomething();
}
};
class Strategyfactory
{
public:
Strategy *make_Strategy(int n)
{
Strategy* tmp;
if(n==1)
{
tmp=new ConcreteStrategy_first();
}
else if(n==2)
{
tmp=new ConcreteStrategy_second();
}
else
{
tmp=new ConcreteStrategy_third();
}
return tmp;
}
};
int main()
{
int input;
Strategyfactory* factory=new Strategyfactory();
cin>>input;
Context* con=new Context(factory->make_Strategy(input));
con->open_text();
return 0;
}
2工厂模式
例子来源于菜鸟教程
#include<iostream>
using namespace std;
class Mouse
{
public:
virtual void make_mouse()=0;
};
class HpMouse:public Mouse
{
public:
void make_mouse()
{
cout<<"HP的鼠标"<<endl;
}
};
class DellMouse:public Mouse
{
public:
void make_mouse()
{
cout<<"DELL的鼠标"<<endl;
}
};
class Factory
{
public:
virtual Mouse* creatMouse()=0;
};
class HpMouseFactory:public Factory
{
public:
Mouse* creatMouse()
{
return new HpMouse();
}
};
class DellMouseFactory:public Factory
{
public:
Mouse* creatMouse()
{
return new DellMouse();
}
};
int main()
{
Factory * factory=new HpMouseFactory();
Mouse* mouse=factory->creatMouse();
mouse->make_mouse();
factory=new DellMouseFactory();
mouse=factory->creatMouse();
mouse->make_mouse();
return 0;
}
3.抽象工厂模式
工厂模式与抽象工厂模式的区别就在于工厂模式是制造单一产品,抽象工厂模式是制造一系列产品,其实它的每一个产品都是一个工厂模式。
#include<iostream>
using namespace std;
class Keyboard
{
public:
virtual void make_key()=0;
};
class HpKeyboard:public Keyboard
{
public:
void make_key()
{
cout<<"惠普键盘"<<endl;
}
};
class DellKeyboard:public Keyboard
{
public:
void make_key()
{
cout<<"戴尔键盘"<<endl;
}
};
class Mouse
{
public:
virtual void make_mouse()=0;
};
class HpMouse:public Mouse
{
public:
void make_mouse()
{
cout<<"HP的鼠标"<<endl;
}
};
class DellMouse:public Mouse
{
public:
void make_mouse()
{
cout<<"DELL的鼠标"<<endl;
}
};
class Factory
{
public:
virtual Mouse* creatMouse()=0;
virtual Keyboard* creatKeyboard()=0;
};
class HpMouseFactory:public Factory
{
public:
Mouse* creatMouse()
{
return new HpMouse();
}
Keyboard* creatKeyboard()
{
return new HpKeyboard();
}
};
class DellMouseFactory:public Factory
{
public:
Mouse* creatMouse()
{
return new DellMouse();
}
Keyboard* creatKeyboard()
{
return new DellKeyboard();
}
};
int main()
{
Factory * factory=new HpMouseFactory();
Mouse* mouse=factory->creatMouse();
Keyboard * key=factory->creatKeyboard();
mouse->make_mouse();
key->make_key();
factory=new DellMouseFactory();
mouse=factory->creatMouse();
key=factory->creatKeyboard();
mouse->make_mouse();
key->make_key();
return 0;
}
4 装饰模式
#include<iostream>
#include<string>
using namespace std;
class Beverage
{
public:
string name;
virtual string getDescription()
{
return this->name;
}
virtual double cost()
{
}
};
class HouseBlend:public Beverage
{
public:
HouseBlend()
{
this->name="House";
}
double cost()
{
return 10.0;
}
};
class Decorate:public Beverage
{
public:
virtual string getDescription()
{
}
};
class Milk :public Decorate
{
private:
Beverage * beverage;
public:
Milk(Beverage * beverage)
{
this->beverage=beverage;
}
string getDescription()
{
return this->beverage->getDescription()+" "+"Milk";
}
double cost()
{
return this->beverage->cost()+2.0;
}
};
class Mocha:public Decorate
{
private:
Beverage * beverage;
public:
Mocha(Beverage * beverage)
{
this->beverage=beverage;
}
string getDescription()
{
return this->beverage->getDescription()+" "+"Mocha";
}
double cost()
{
return this->beverage->cost()+5.0;
}
};
int main()
{
Beverage* ber=new HouseBlend();
cout<<ber->getDescription()<<endl;
cout<<ber->cost()<<endl;
ber=new Milk(ber);
cout<<ber->getDescription()<<endl;
cout<<ber->cost()<<endl;
ber=new Mocha(ber);
cout<<ber->getDescription()<<endl;
cout<<ber->cost()<<endl;
return 0;
}
5.代理模式
例子,代理买房子
#include<iostream>
#include<string>
using namespace std;
class Buy
{
public:
virtual void buy_building()=0;
};
class Realbuy:public Buy
{
private:
string name;
public:
Realbuy(string name)
{
this->name=name;
}
void buy_building()
{
cout<<this->name<<"买房"<<endl;
}
};
class Proxy:public Buy
{
private:
Realbuy * buy;
public:
Proxy(string name)
{
this->buy=new Realbuy(name);
}
void buy_building()
{
cout<<"我是代理,代替买房"<<endl;
this->buy->buy_building();
}
};
int main()
{
Proxy* proxy=new Proxy("lisi");
proxy->buy_building();
return 0;
}
6模板模式
模板模式是利用父类将整个基本算法的每一步全部实现,其中某一部分由子类实现,这样实现代码复用的最大。
在父类中可以利用钩子来控制算法,根据子类复写的钩子函数的返回值,来确定算法某个步骤是否执行。
#include<iostream>
#include<string>
using namespace std;
class Operate
{
public:
void open_on()
{
init_system();
show_log();
if(hook()==true)
{
input_mima();
}
show_desktop();
}
void init_system()
{
cout<<"系统初始化"<<endl;
}
virtual void show_log()
{
}
void input_mima()
{
cout<<"请输入密码"<<endl;
}
void show_desktop()
{
cout<<"桌面"<<endl;
}
virtual bool hook()
{
}
};
class Mobile:public Operate
{
private:
int mima;
public:
Mobile(int mima)
{
this->mima=mima;
}
void set_mima(int mima)
{
this->mima=mima;
}
void show_log()
{
cout<<"手机操作系统"<<endl;
}
bool hook()
{
if(this->mima==1)
{
return true;
}
else
{
return false;
}
}
};
class Computer:public Operate
{
private:
int mima;
public:
Computer(int mima)
{
this->mima=mima;
}
void set_mima(int mima)
{
this->mima=mima;
}
void show_log()
{
cout<<"电脑操作系统"<<endl;
}
bool hook()
{
if(this->mima==1)
{
return true;
}
else
{
return false;
}
}
};
int main()
{
Mobile * mobile=new Mobile(1);
mobile->open_on();
mobile->set_mima(0);
mobile->open_on();
Computer* computer=new Computer(0);
computer->open_on();
computer->set_mima(0);
computer->open_on();
return 0;
}
- 门面模式
将复杂的类之间的关系封装起来,客户只需通过一个门面来进行访问,隐藏了具体的细节。
例子,打开电视,目前的电视都采用电视加数字机顶盒以及网络转接盒的配置,打开电视观看节目需要打开电视、打开机顶盒、打开网络转换盒才可以收看电视。因此客户每次打开电视的步骤就很繁琐了,利用门面模式解决这个问题。
#include<iostream>
#include<string>
using namespace std;
class Tv
{
public:
void open_tv()
{
cout<<"打开电视"<<endl;
}
void close_tv()
{
cout<<"关闭电视"<<endl;
}
};
class Proxy
{
public:
void open_proxy()
{
cout<<"打开网络转换器"<<endl;
}
void close_proxy()
{
cout<<"关闭网络转换器"<<endl;
}
};
class Box
{
public:
void open_box()
{
cout<<"打开机顶盒"<<endl;
}
void close_box()
{
cout<<"关闭机顶盒"<<endl;
}
};
class Power
{
private:
Tv* tv;
Box* box;
Proxy* proxy;
public:
Power()
{
this->tv=new Tv();
this->box=new Box();
this->proxy=new Proxy();
}
void open_power()
{
this->tv->open_tv();
this->box->open_box();
this->proxy->open_proxy();
cout<<"可以看电视了"<<endl;
}
void close_power()
{
this->box->close_box();
this->proxy->close_proxy();
this->tv->close_tv();
cout<<"关机了"<<endl;
}
};
int main()
{
Power* power=new Power();
power->open_power();
power->close_power();
return 0;
}
8 建造者模式
建造者模式可以把建造的过程封装起来,动态的选择加工的过程,方便扩展。
#include<iostream>
#include<string>
using namespace std;
class Mobile
{
private:
string name;
string memory;
string operate;
public:
void set_name(string name)
{
this->name=name;
}
void set_memory(string memory)
{
this->memory=memory;
}
void set_operate(string operate)
{
this->operate=operate;
}
string get_Mobile()
{
return this->name+" "+this->memory+" "+this->operate;
}
};
class Builder
{
public:
virtual void build_name()=0;
virtual void build_memory()=0;
virtual void build_operate()=0;
virtual Mobile* get_product()=0;
};
class HuaweiMobileBuilder:public Builder
{
private:
Mobile *mobile;
public:
HuaweiMobileBuilder()
{
this->mobile=new Mobile();
}
void build_name()
{
this->mobile->set_name("MATE 30");
}
void build_memory()
{
this->mobile->set_memory("8G");
}
void build_operate()
{
this->mobile->set_operate("EIMU10");
}
Mobile * get_product()
{
return this->mobile;
}
};
class AppleMobileBuilder:public Builder
{
private:
Mobile *mobile;
public:
AppleMobileBuilder()
{
this->mobile=new Mobile();
}
void build_name()
{
this->mobile->set_name("apple");
}
void build_memory()
{
this->mobile->set_memory("4G");
}
void build_operate()
{
this->mobile->set_operate("IOS");
}
Mobile * get_product()
{
return this->mobile;
}
};
class Director
{
public:
Mobile * construct(Builder * builder)
{
builder->build_name();
builder->build_memory();
builder->build_operate();
return builder->get_product();
}
};
int main()
{
Director *dir=new Director();
Builder * builder=new HuaweiMobileBuilder();
Mobile *mobile=dir->construct(builder);
cout<<mobile->get_Mobile()<<endl;
builder=new AppleMobileBuilder();
mobile=dir->construct(builder);
cout<<mobile->get_Mobile()<<endl;
return 0;
}
9 观察者模式
可以动态添加观察者,当被观察的对象发生改变时,通知所有的观察者,引起他们的动作。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Observer
{
public:
virtual void update()=0;
};
class ConcreteObserver:public Observer
{
private:
string name;
public:
ConcreteObserver(string name)
{
this->name=name;
}
void update()
{
cout<<this->name<<"接到通知"<<endl;
}
};
class Object
{
public:
vector<Observer *> obj;
virtual void notify()=0;
virtual void add_observer(Observer *)=0;
virtual void del_observer()=0;
};
class ConcreteObject:public Object
{
public:
void add_observer(Observer * observer)
{
this->obj.push_back(observer);
}
void del_observer()
{
this->obj.pop_back();
}
void notify()
{
for(auto i=this->obj.begin();i<this->obj.end();i++)
{
(*i)->update();
}
}
};
int main()
{
Observer * observer=new ConcreteObserver("lisi");
Object * object=new ConcreteObject();
object->add_observer(observer);
observer=new ConcreteObserver("zhangsan");
object->add_observer(observer);
object->notify();
object->del_observer();
object->notify();
return 0;
}
10状态模式
学生上学,在8点到11点上课,11点到2点午餐,2点到5点上课,其余时间休息
#include<iostream>
using namespace std;
class Student;
class State
{
public:
virtual void handle(Student * student)=0;
};
class Student
{
private:
State * state;
double hour;
public:
Student(State * state)
{
this->state=state;
}
void set_hour(double hour)
{
this->hour=hour;
}
int get_hour()
{
return this->hour;
}
void set_state(State * state)
{
this->state=state;
}
void get_state()
{
this->state->handle(this);
}
};
class Onbreak:public State
{
public:
void handle(Student * student)
{
cout<<"休息了"<<endl;
}
};
class Onclass_afternoon:public State
{
public:
void handle(Student * student)
{
if(student->get_hour()<=17)
{
cout<<"上课呢下午"<<endl;
}
else
{
student->set_state(new Onbreak);
student->get_state();
}
}
};
class Onlunch:public State
{
public:
void handle(Student * student)
{
if(student->get_hour()<=14)
{
cout<<"午休"<<endl;
}
else
{
student->set_state(new Onclass_afternoon);
student->get_state();
}
}
};
class Onclass_morning:public State
{
public:
void handle(Student * student)
{
if(student->get_hour()<=11)
{
cout<<"上课呢上午"<<endl;
}
else
{
student->set_state(new Onlunch);
student->get_state();
}
}
};
int main()
{
Student * student=new Student(new Onclass_morning());
for(int i=8;i<20;i+=2)
{
student->set_hour(i);
student->get_state();
}
return 0;
}
想模仿在head first 设计模式中的状态模式,里面每个状态转换都是通过调用student_setOnlunch()这种函数改变状态,这样每个状态类不需要知道其他状态类的存在,但是在C++里面,它不能使用前面没声明的类中的函数,所以不知道怎么办。
11 适配器模式
硬件接口适配。
#include<iostream>
using namespace std;
class Target
{
public:
virtual void get_decoder()=0;
};
class Adpatee
{
public:
void get_my_status(int address)
{
if(address==10)
{
cout<<"编码器数据为5000"<<endl;
}
else if(address==11)
{
cout<<"电机转速为10"<<endl;
}
else{
return;
}
}
};
class Adpate:public Target
{
private:
Adpatee* adpatee;
public:
Adpate()
{
this->adpatee=new Adpatee();
}
void get_decoder()
{
this->adpatee->get_my_status(10);
}
};
int main()
{
Adpate * adpate=new Adpate();
adpate->get_decoder();
return 0;
}
12 备忘录模式
#include<iostream>
using namespace std;
class Memento
{
private:
string state;
public:
Memento(string state)
{
this->state=state;
}
string get_menmento_state()
{
return this->state;
}
};
class Originator
{
private:
string state;
public:
void set_state(string state)
{
this->state=state;
}
string get_state()
{
return this->state;
}
Memento * creat_memento()
{
return new Memento(this->state);
}
void read_memento(Memento * memento)
{
this->state=memento->get_menmento_state();
}
};
class Caretaker
{
private:
Memento * memento;
public:
void set_memento(Memento * memento)
{
this->memento=memento;
}
Memento * get_memento()
{
return this->memento;
}
};
int main()
{
Originator* ori=new Originator();
ori->set_state("zhangsan");
Caretaker* care=new Caretaker();
care->set_memento(ori->creat_memento());
ori->set_state("lisi");
cout<<ori->get_state()<<endl;
ori->read_memento(care->get_memento());
cout<<ori->get_state()<<endl;
return 0;
}
13 组合模式
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
class Component
{
public:
virtual void add(Component * )=0;
virtual void del(Component *)=0;
virtual void paybycard()=0;
};
class Leaf:public Component
{
private:
string name;
public:
Leaf(string name)
{
this->name=name;
}
void add(Component * com)
{
cout<<"叶子节点不能添加"<<endl;
}
void del(Component *com)
{
cout<<"叶子节点不能删除"<<endl;
}
void paybycard()
{
cout<<this->name<<"消费累加到会员卡"<<endl;
}
};
class Composite:public Component
{
private:
vector<Component *> list_compoment;
string name;
public:
Composite(string name)
{
this->name=name;
}
void add(Component * com)
{
list_compoment.push_back(com);
}
void del(Component * com)
{
auto it=find(list_compoment.begin(),list_compoment.end(),com);
list_compoment.erase(it);
}
void paybycard()
{
cout<<this->name<<"消费累加到会员卡"<<endl;
for(auto it=list_compoment.begin();it<list_compoment.end();it++)
{
(*it)->paybycard();
}
}
};
int main()
{
Component * root=new Composite("总店");
Component * harbin=new Composite("哈尔滨店");
Component * daqing=new Composite("大庆分店");
daqing->add(new Leaf("萨尔图门店"));
daqing->add(new Leaf("让胡路门店"));
harbin->add(daqing);
Component * qiqihaer=new Composite("齐齐哈尔分店");
harbin->add(qiqihaer);
harbin->paybycard();
harbin->del(qiqihaer);
harbin->paybycard();
return 0;
}
14 单例模式
#include<iostream>
using namespace std;
class Singleton
{
private:
static Singleton * instance;
public:
static Singleton* get_instance()
{
if(instance==NULL)
{
instance=new Singleton();
}
return instance;
}
};
Singleton * Singleton::instance=NULL;
int main()
{
Singleton * tmp=Singleton::get_instance();
Singleton * second=Singleton::get_instance();
if(tmp==second)
{
cout<<"the same"<<endl;
}
return 0;
}
15 桥接模式
#include<iostream>
using namespace std;
class Abstractcar
{
public:
virtual void run()=0;
};
class Car:public Abstractcar
{
public:
void run()
{
cout<<"小汽车"<<endl;
}
};
class Bus:public Abstractcar
{
public:
void run()
{
cout<<"公共汽车"<<endl;
}
};
class Abstractroad
{
public:
Abstractcar * iscar;
virtual void run()=0;
void set_iscar(Abstractcar * iscar)
{
this->iscar=iscar;
}
};
class Speedway:public Abstractroad
{
public:
void run()
{
this->iscar->run();
cout<<"在高速路奔驰"<<endl;
}
};
class Street:public Abstractroad
{
public:
void run()
{
this->iscar->run();
cout<<"在街道奔驰"<<endl;
}
};
int main()
{
Abstractroad* road=new Street();
road->set_iscar(new Car());
road->run();
road=new Street();
road->set_iscar(new Bus());
road->run();
return 0;
}
16 命令模式
#include<iostream>
using namespace std;
class Light
{
public:
void on()
{
cout<<"灯打开了"<<endl;
}
void off()
{
cout<<"灯关了"<<endl;
}
};
class Command
{
public:
virtual void execute()=0;
};
class LightonCommand:public Command
{
private:
Light* light;
public:
LightonCommand(Light * light)
{
this->light=light;
}
void execute()
{
this->light->on();
}
};
class LightoffCommand:public Command
{
private:
Light *light;
public:
LightoffCommand(Light* light)
{
this->light=light;
}
void execute()
{
this->light->off();
}
};
class Invoker
{
private:
Command *command;
public:
void action()
{
this->command->execute();
}
void set_command(Command * command)
{
this->command=command;
}
};
int main()
{
Light* light=new Light();
LightonCommand * lighton=new LightonCommand(light);
LightoffCommand * lightoff=new LightoffCommand(light);
Invoker * invoker=new Invoker();
invoker->set_command(lighton);
invoker->action();
invoker->set_command(lightoff);
invoker->action();
return 0;
}
17 责任链模式
学生请假,由班主任校长审批
#include<iostream>
using namespace std;
class Request
{
private:
string name;
string request;
int days;
public:
Request(string name)
{
this->name=name;
}
void set_request(string request)
{
this->request=request;
}
string get_request()
{
return this->request;
}
string get_name()
{
return this->name;
}
void set_days(int days)
{
this->days=days;
}
int get_days()
{
return this->days;
}
};
class Manager
{
public:
string name;
Manager * req;
Manager(string name)
{
this->name=name;
this->req=nullptr;
}
void set_req(Manager *req)
{
this->req=req;
}
virtual void handlerequest(Request * request)=0;
};
class Teacher:public Manager
{
public:
Teacher(string name):Manager(name)
{
}
void handlerequest(Request * request)
{
if(request->get_request()=="请假"&&request->get_days()<3)
{
cout<<this->name<<"批准了"<<request->get_name()<<"的请假"<<request->get_days()<<"天"<<endl;
}
else
{
if(this->req!=nullptr)
{
this->req->handlerequest(request);
}
}
}
};
class Schoolmaster:public Manager
{
public:
Schoolmaster(string name):Manager(name)
{
}
void handlerequest(Request * request)
{
if(request->get_request()=="请假"&&request->get_days()<10)
{
cout<<this->name<<"批准了"<<request->get_name()<<"的请假"<<request->get_days()<<"天"<<endl;
}
else
{
cout<<"不能批准"<<endl;
}
}
};
int main()
{
Manager* teacher=new Teacher("李老师");
Manager* schoolmaster=new Schoolmaster("张校长");
teacher->set_req(schoolmaster);
Request * request=new Request("李四");
request->set_request("请假");
request->set_days(2);
teacher->handlerequest(request);
request=new Request("张三");
request->set_request("请假");
request->set_days(8);
teacher->handlerequest(request);
request=new Request("王五");
request->set_request("请假");
request->set_days(20);
teacher->handlerequest(request);
return 0;
}
18中介者模式
#include<iostream>
using namespace std;
class Media;
class Colleague
{
public:
Media * media;
void set_media(Media * media)
{
this->media=media;
}
virtual void notify(string name)=0;
virtual void receive(string message)=0;
};
class Media
{
public:
virtual void send(string message,Colleague * colleague)=0;
};
class America:public Colleague
{
public:
void notify(string name)
{
this->media->send(name,this);
}
void receive(string name)
{
cout<<"美国收到消息:"<<name<<endl;
}
};
class Iraq:public Colleague
{
public:
void notify(string name)
{
this->media->send(name,this);
}
void receive(string name)
{
cout<<"伊拉克收到消息:"<<name<<endl;
}
};
class National:public Media
{
private:
Colleague *A;
Colleague *B;
public:
National(Colleague * A,Colleague *B)
{
this->A=A;
this->B=B;
}
void send(string message,Colleague * colleague)
{
if(colleague==this->A)
{
this->B->receive(message);
}
else
{
this->A->receive(message);
}
}
};
int main()
{
Colleague *usa=new America();
Colleague *iraq=new Iraq();
Media* national=new National(usa,iraq);
usa->set_media(national);
iraq->set_media(national);
usa->notify("我要撤军了");
iraq->notify("抓紧撤军");
return 0;
}
19 享元模式
#include<iostream>
#include<map>
using namespace std;
class Location
{
private:
int x,y;
public:
Location(int x,int y)
{
this->x=x;
this->y=y;
}
int get_x()
{
return this->x;
}
int get_y()
{
return this->y;
}
void set_x(int x)
{
this->x=x;
}
void set_y(int y)
{
this->y=y;
}
};
class Flyweight
{
public:
string color;
virtual string get_color()=0;
virtual void display(Location* locate)=0;
};
class ConcreteFlyweight:public Flyweight
{
public:
ConcreteFlyweight(string color)
{
this->color=color;
}
string get_color()
{
return this->color;
}
void display(Location * locate)
{
cout<<this->color<<"棋的位置在"<<"x"<<locate->get_x()<<","<<"y"<<locate->get_y()<<endl;
}
};
class FlyweightFactory
{
private:
map<string,Flyweight*> chess;
public:
Flyweight* get_flyweight(string color)
{
if(chess.count(color)!=0)
{
return chess[color];
}
else
{
chess[color]=new ConcreteFlyweight(color);
return chess[color];
}
}
};
int main()
{
FlyweightFactory* factory=new FlyweightFactory();
Flyweight* chess=factory->get_flyweight("黑色");
Flyweight* chess_w=factory->get_flyweight("黑色");
if(chess==chess_w)
{
cout<<"黑色棋子"<<endl;
}
chess->display(new Location(4,5));
return 0;
}