设计模式(c++实现)
总述
总体来说设计模式分为三大类:
分类
创建型模式
共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。
结构型模式
共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
行为型模式
共十一种:模板方法模式、策略模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
六大原则
总原则:开闭原则
开闭原则就是说对扩展开放,对修改关闭
单一职责原则
一个类应该只有一个发生变化的原因,即每一个职责都是变化的一个轴线,如果一个类有一个以上的职责,这些职责就耦合在了一起。这会导致脆弱的设计
里氏替换原则
派生类(子类)对象可以在程序中代替其基类(超类)对象。因为继承带来的侵入性,增加了耦合性,也降低了代码灵活性,父类修改代码,子类也会受到影响,此时就需要里氏替换原则。
- 子类必须实现父类的抽象方法,但不得重写(覆盖)父类的非抽象(已实现)方法。
- 子类中可以增加自己特有的方法。
- 当子类覆盖或实现父类的方法时,方法的前置条件(即方法的形参)要比父类方法的输入参数更宽松。
- 当子类的方法实现父类的抽象方法时,方法的后置条件(即方法的返回值)要比父类更严格。
依赖倒转原则
程序要依赖于抽象接口,不要依赖于具体实现。简单的说就是要求对抽象进行编程,不要对实现进行编程,这样就降低了客户与实现模块间的耦合。
public interface ICourse {
void study();
}
public class MathCourse implements ICourse {
@Override
public void study() {
System.out.println("学习math课程");
}
}
public class ChineseCourse implements ICourse {
@Override
public void study() {
System.out.println("学习Chinese课程");
}
}
public class GoStudy {
public void study(ICourse course) {
course.study();
}
public static void main(String[] args) {
GoStudy mGoStudy = new GoStudy();
mGoStudy.study(new MathCourse());
mGoStudy.study(new ChineseCourse());
}
}
接口隔离原则
客户端需要什么功能,就提供什么接口,对于客户端不需要的接口不应该强行要求其依赖;类之间的依赖应该建立在最小的接口上面,这里最小的粒度取决于单一职责原则的划分。即每个接口中不存在子类用不到却必须实现的方法,如果不然,就要将接口拆分。使用多个隔离的接口,比使用单个接口(多个接口方法集合到一个的接口)要好。
迪米特法则
一个对象应该对其他对象有最少的了解。它的意义是降低类之间的耦合,由于每个对象应该尽量减少对其他对象的了解,因此,很容易使得系统的功能模块独立,相互之间不存在或者很少的依赖关系。
那么怎么做到一个对象对其他对象的了解最少呢?我们把对象比作我们自己,要想实现对其他人有更少的了解,做到两点就够了:1. 只和直接的朋友交流;2.减少对朋友的了解。
合成复用原则
原则是尽量首先使用合成/聚合的方式,而不是使用继承。
创建型模式
工厂方法模式
c++实现
#include <iostream>
#include <cstring>
using namespace std;
class Shoe {
public:
virtual void show() = 0;
};
//鞋子A
class ShoeA: public Shoe {
public:
void show() {
cout << "Shoe A" << endl;
}
};
//鞋子B
class ShoeB: public Shoe {
public:
void show() {
cout << "Shoe B" << endl;
}
};
class Factory {
public:
virtual Shoe* CreateShoe() = 0;
};
//生产A鞋的工厂
class FactoryA: public Factory {
public:
ShoeA* CreateShoe() {
return new ShoeA;
}
};
//生产B鞋的工厂
class FactoryB: public Factory {
public:
ShoeB* CreateShoe() {
return new ShoeB;
}
};
int main() {
Factory *fa = NULL;
Shoe *shoe = NULL;
fa = new FactoryA();
shoe = fa->CreateShoe();
shoe->show();
fa = new FactoryB();
shoe = fa->CreateShoe();
shoe->show();
return 0;
}
抽象工厂模式
c++实现
#include <iostream>
#include <cstring>
using namespace std;
class Shoe {
public:
virtual void show() = 0;
};
//鞋子A
class ShoeA: public Shoe {
public:
void show() {
cout << "Shoe A" << endl;
}
};
//鞋子B
class ShoeB: public Shoe {
public:
void show() {
cout << "Shoe B" << endl;
}
};
class Sock {
public:
virtual void show() = 0;
};
//袜子A
class SockA: public Sock {
public:
void show() {
cout << "Sock A" << endl;
}
};
//袜子B
class SockB: public Sock {
public:
void show() {
cout << "Sock B" << endl;
}
};
class Factory {
public:
virtual Shoe* CreateShoe() = 0;
virtual Sock* CreateSock() = 0;
};
//生产工厂A
class FactoryA: public Factory {
public:
ShoeA* CreateShoe() {
return new ShoeA;
}
SockA* CreateSock() {
return new SockA;
}
};
//生产工厂B
class FactoryB: public Factory {
public:
ShoeB* CreateShoe() {
return new ShoeB;
}
SockB* CreateSock() {
return new SockB;
}
};
int main() {
Factory *fa = NULL;
Shoe *shoe = NULL;
Sock *sock = NULL;
fa = new FactoryA();
shoe = fa->CreateShoe();
shoe->show();
sock = fa->CreateSock();
sock->show();
fa = new FactoryB();
shoe = fa->CreateShoe();
shoe->show();
sock = fa->CreateSock();
sock->show();
return 0;
}
单例模式
c++实现
#include <iostream>
#include <string>
using namespace std;
class Singleton {
public:
static Singleton* GetInstance();
void show();
private:
Singleton() {
}
static Singleton *singleton;
};
void Singleton::show() {
cout << "I build singleton" << endl;
}
Singleton* Singleton::singleton = NULL;
Singleton* Singleton::GetInstance() {
if (singleton == NULL)
singleton = new Singleton();
return singleton;
}
int main() {
Singleton* mSingleton = Singleton::GetInstance();
mSingleton->show();
delete mSingleton;
}
建造者模式
c++实现
#include <iostream>
#include <string>
using namespace std;
class Builder {
public:
virtual void buildWheel()=0;
virtual void buildEngine()=0;
virtual void buildBody()=0;
virtual ~Builder() {
}
};
class BenBuilder: public Builder {
public:
void buildWheel() {
cout << "Ben wheel" << endl;
}
void buildEngine() {
cout << "Ben engine" << endl;
}
void buildBody() {
cout << "Ben body" << endl;
}
};
class FordBuilder: public Builder {
public:
void buildWheel() {
cout << "Ford wheel" << endl;
}
void buildEngine() {
cout << "Ford engine" << endl;
}
void buildBody() {
cout << "Ford body" << endl;
}
~FordBuilder() {
}
};
class Demander {
private:
Builder *m_builder;
public:
Demander(Builder *builder);
virtual ~Demander();
void build();
};
Demander::Demander(Builder *builder) {
m_builder = builder;
}
Demander::~Demander() {
if (m_builder) {
delete m_builder;
}
}
void Demander::build() {
if (m_builder) {
m_builder->buildBody();
m_builder->buildEngine();
m_builder->buildWheel();
} else {
cout << "build error" << endl;
}
}
int main() {
BenBuilder mBenBuilder;
Demander mDemander(mBenBuilder);
mDemander.build();
FordBuilder mFordBuilder;
Demander gDemander(&mFordBuilder);
gDemander.build();
}
原型模式
c++ 实现
#include <iostream>
#include <string>
using namespace std;
class Prototype {
private:
std::string m_name;
public:
Prototype(std::string name = "") :
m_name(name) {
}
void show() {
cout << m_name << endl;
}
virtual Prototype *clone() = 0;
};
class PrototypeA: public Prototype {
public:
PrototypeA(std::string name = "") :
Prototype(name) {
}
Prototype *clone();
};
Prototype* PrototypeA::clone() {
PrototypeA *p = new PrototypeA();
*p = *this;
return p;
}
class PrototypeB: public Prototype {
public:
PrototypeB(std::string name = "") :
Prototype(name) {
}
Prototype *clone();
};
Prototype* PrototypeB::clone() {
PrototypeB *p = new PrototypeB();
*p = *this;
return p;
}
int main() {
PrototypeA *testA = new PrototypeA("小冯");
PrototypeB *testB = (PrototypeB *) testA->clone();
testA->show();
testB->show();
delete testA;
delete testB;
}
结构型模式
适配器模式
#include <iostream>
#include <string>
using namespace std;
class SystemA {
public:
virtual void getName() {
cout << "获取系统A中某员工的名称" << endl;
}
};
class SystemB {
public:
virtual void getAliasName() {
cout << "获取系统B中某员工的别名" << endl;
}
};
/***适配器:Adapter***/
class AdapterSystem: public SystemA {
public:
AdapterSystem(SystemB *sysB) :
m_sysB(sysB) {
}
virtual void getName() {
m_sysB->getAliasName();
}
private:
SystemB *m_sysB;
};
/****系统A工作场景****/
int main() {
SystemB *sysB = new SystemB;
//创建适配器
SystemA *sysA = new AdapterSystem(sysB);
sysA->getName();
return 0;
}
装饰器模式
#include <iostream>
#include <string>
using namespace std;
//手机
class Phone {
public:
Phone() {
}
virtual ~Phone() {
}
virtual void showDecorate() {
}
};
//苹果手机
class IPhone: public Phone {
private:
string m_name;
public:
IPhone(string name) :
m_name(name) {
}
~IPhone() {
}
void showDecorate() {
cout << m_name << "的装饰" << endl;
}
};
//Oppo手机
class OppoPhone: public Phone {
private:
string m_name;
public:
OppoPhone(string name) :
m_name(name) {
}
~OppoPhone() {
}
void showDecorate() {
cout << m_name << "的装饰" << endl;
}
};
//装饰类
class DecoratorPhone: public Phone {
private:
Phone *m_phone; //要装饰的手机
public:
DecoratorPhone(Phone *phone) :
m_phone(phone) {
}
void showDecorate() {
m_phone->showDecorate();
}
};
//具体的装饰类
class DecoratorPhoneA: public DecoratorPhone {
public:
DecoratorPhoneA(Phone *phone) :
DecoratorPhone(phone) {
}
void showDecorate() {
DecoratorPhone::showDecorate();
addDecorate();
}
private:
//增加的装饰
void addDecorate() {
cout << "增加挂件" << endl;
}
};
//具体的装饰类
class DecoratorPhoneB: public DecoratorPhone {
public:
DecoratorPhoneB(Phone *phone) :
DecoratorPhone(phone) {
}
void showDecorate() {
DecoratorPhone::showDecorate();
addDecorate();
}
private:
//增加的装饰
void addDecorate() {
cout << "屏幕贴膜" << endl;
}
};
int main() {
Phone *phone = new OppoPhone("Reno5");
Phone *pa = new DecoratorPhoneA(phone); //装饰,增加挂件
Phone *pb = new DecoratorPhoneB(pa); //装饰,屏幕贴膜
pb->showDecorate();
delete pa;
delete pb;
delete phone;
return 0;
}
代理模式
#include <iostream>
#include <string>
using namespace std;
class Image {
public:
Image(string name) :
m_name(name) {
}
virtual ~Image() {
}
virtual void Show() {
}
protected:
string m_name;
};
class SmallImage: public Image {
public:
SmallImage(string name) :
Image(name) {
}
~SmallImage() {
}
void Show() {
cout << "to show how small image : " << m_name << endl;
}
};
class SmallImageProxy: public Image {
private:
SmallImage *m_smallImage;
public:
SmallImageProxy(string name) :
Image(name), m_smallImage(NULL) {
}
~SmallImageProxy() {
delete m_smallImage;
}
void Show() {
if (m_smallImage == NULL) {
m_smallImage = new SmallImage(m_name);
}
m_smallImage->Show();
}
};
int main() {
Image *image = new SmallImageProxy("proxy.jpg");
image->Show();
delete image;
return 0;
}
外观模式
#include <iostream>
#include <string>
using namespace std;
class Sub_work1 {
public:
void work1() {
cout << "work1 is starting!" << endl;
}
};
class Sub_work2 {
public:
void work2() {
cout << "work2 is starting!" << endl;
}
};
class Sub_work3 {
public:
void work3() {
cout << "work3 is starting!" << endl;
}
};
class MainWork {
public:
void work() {
w1.work1();
w2.work2();
w3.work3();
}
private:
Sub_work1 w1;
Sub_work2 w2;
Sub_work3 w3;
};
int main() {
MainWork mainWork;
mainWork.work();
return 0;
}
桥接模式
#include <iostream>
#include <string>
using namespace std;
class OS {
public:
virtual ~OS() {
}
OS() {
}
virtual void installOs()=0;
};
class IOS: public OS {
public:
IOS() {
}
virtual ~IOS() {
}
void installOs() {
cout << "install IOS" << endl;
}
};
class Android: public OS {
public:
Android() {
}
virtual ~Android() {
}
void installOs() {
cout << "install Android" << endl;
}
};
class Harmony: public OS {
public:
Harmony() {
}
virtual ~Harmony() {
}
void installOs() {
cout << "install Harmony" << endl;
}
};
class Phone {
public:
virtual ~Phone() {
}
Phone() {
}
virtual void needWhichOs(OS *os) {
}
virtual void showName()=0;
};
class HuaWei: public Phone {
public:
void needWhichOs(OS *os) {
showName();
os->installOs();
}
void showName() {
cout << "HuaWei ";
}
};
class GooglePhone: public Phone {
public:
void needWhichOs(OS *os) {
showName();
os->installOs();
}
void showName() {
cout << "GooglePhone ";
}
};
class Iphone: public Phone {
public:
void needWhichOs(OS *os) {
showName();
os->installOs();
}
void showName() {
cout << "Iphone ";
}
};
int main() {
OS *ios = new IOS();
OS *android = new Android();
OS *harmony = new Harmony();
Phone *huawei = new HuaWei();
Phone *googlephone = new GooglePhone();
Phone *iphone = new Iphone();
huawei->needWhichOs(harmony);
googlephone->needWhichOs(android);
iphone->needWhichOs(ios);
//将两个不相关的东西桥接起来,还可以
cout << "================" << endl;
huawei->needWhichOs(ios);
googlephone->needWhichOs(harmony);
iphone->needWhichOs(android);
delete ios;
delete android;
delete harmony;
delete huawei;
delete googlephone;
delete iphone;
return 0;
}
组合模式
#include <iostream>
#include <list>
#include <string>
using namespace std;
class Department {
public:
Department(string name) {
m_name = name;
}
virtual ~Department() {
}
virtual void add(Department *dpt) {
}
virtual void show(int depth) {
}
protected:
string m_name;
};
class ConcreteCompany: public Department {
public:
ConcreteCompany(string name) :
Department(name) {
}
virtual ~ConcreteCompany() {
}
void add(Department *dpt) {
m_listCompany.push_back(dpt);
}
void show(int depth) {
for (int i = 0; i < depth; i++)
cout << "-";
cout << m_name << endl;
list<Department *>::iterator iter = m_listCompany.begin();
for (; iter != m_listCompany.end(); iter++)
(*iter)->show(depth + LINE);
}
private:
list<Department *> m_listCompany;
const int LINE = 2;
};
//具体的部门,财务部
class FinanceDepartment: public Department {
public:
FinanceDepartment(string name) :
Department(name) {
}
virtual ~FinanceDepartment() {
}
virtual void show(int depth) {
for (int i = 0; i < depth; i++)
cout << "-";
cout << m_name << endl;
}
};
//具体的部门,人力资源部
class HRDepartment: public Department {
public:
HRDepartment(string name) :
Department(name) {
}
virtual ~HRDepartment() {
}
virtual void show(int depth) {
for (int i = 0; i < depth; i++)
cout << "-";
cout << m_name << endl;
}
};
int main() {
Department *root = new ConcreteCompany("总公司");
Department *leaf1 = new FinanceDepartment("财务部");
Department *leaf2 = new HRDepartment("人力资源部");
root->add(leaf1);
root->add(leaf2);
//分公司A
Department *mid1 = new ConcreteCompany("分公司A");
Department *leaf3 = new FinanceDepartment("财务部");
Department *leaf4 = new HRDepartment("人力资源部");
mid1->add(leaf3);
mid1->add(leaf4);
root->add(mid1);
//分公司B
Department *mid2 = new ConcreteCompany("分公司B");
FinanceDepartment *leaf5 = new FinanceDepartment("财务部");
HRDepartment *leaf6 = new HRDepartment("人力资源部");
mid2->add(leaf5);
mid2->add(leaf6);
root->add(mid2);
root->show(0);
delete leaf1;
delete leaf2;
delete leaf3;
delete leaf4;
delete leaf5;
delete leaf6;
delete mid1;
delete mid2;
delete root;
return 0;
}
享元模式
#include <iostream>
#include <map>
#include <string>
using namespace std;
class Flyweight {
public:
virtual void operation(int extrinsicstate) = 0;
virtual ~Flyweight() {
}
};
class ConcreteFlyweight: public Flyweight {
public:
void operation(int extrinsicstate) {
cout << "ConcreteFlyweight: " << extrinsicstate << endl;
}
};
class UnsharedConcreteFlyweight: public Flyweight { // 不强制共享对象,但也可以共享
public:
void operation(int extrinsicstate) {
cout << "UnsharedConcreteFlyweight: " << extrinsicstate << endl;
}
};
class FlyweightFactory {
private:
map<string, Flyweight*> flyweights;
public:
Flyweight* getFlyweight(string key) {
if (flyweights[key] == NULL)
flyweights[key] = new ConcreteFlyweight();
return flyweights[key];
}
};
int main() {
int extrinsicstate = 22; // 外部状态
FlyweightFactory* f = new FlyweightFactory();
Flyweight* fx = f->getFlyweight("X");
fx->operation(--extrinsicstate);
Flyweight* fy = f->getFlyweight("Y");
fy->operation(--extrinsicstate);
Flyweight* fz = f->getFlyweight("Z");
fz->operation(--extrinsicstate);
UnsharedConcreteFlyweight* uf = new UnsharedConcreteFlyweight();
uf->operation(--extrinsicstate);
delete fx;
delete fy;
delete fz;
delete f;
delete uf;
return 0;
}
行为型模式
模板方法模式
模板方法模式的一个重要特征是它的定义在基类中(有时作为一个私有成员函数)并且不能改动,模板方法模式就是“坚持相同的代码“。它调用其他基类函数(就是那些被覆盖的函数)以便完成其工作,但是客户程序员不必直接调用这些函数。
#include <iostream>
#include <string>
using namespace std;
class ApplicationFramework {
protected:
virtual void testWifi()=0;
virtual void testBluetooth()=0;
public:
void templateMethod() {
testWifi();
testBluetooth();
}
};
class MyApp: public ApplicationFramework {
protected:
void testWifi() {
cout << "test wifi" << endl;
}
void testBluetooth() {
cout << "test bluetooth" << endl;
}
};
int main() {
MyApp app;
app.templateMethod();
}
策略模式
#include <iostream>
#include <map>
#include <string>
using namespace std;
class Algorithm {
public:
virtual void execute()=0;
};
class AlgorithmA: public Algorithm {
public:
void execute() {
cout << "AlgorithmA is running" << endl;
}
};
class AlgorithmB: public Algorithm {
public:
void execute() {
cout << "AlgorithmB is running" << endl;
}
};
class AlgorithmC: public Algorithm {
public:
void execute() {
cout << "AlgorithmC is running" << endl;
}
};
template<typename ALGO>
class Artificial {
private:
ALGO mALGO;
public:
void run() {
mALGO.execute();
}
};
int main() {
Artificial<AlgorithmC> mAlgorithmC;
mAlgorithmC.run();
return 0;
}
观察者模式
#include <iostream>
#include <list>
#include <string>
using namespace std;
// 抽象观察者
class IObserver {
public:
virtual void update(float percent) = 0; // 更新股票
virtual ~IObserver() {
}
};
class IObserver;
// 抽象主题
class ISubject {
public:
virtual void attach(IObserver *) = 0; // 注册观察者
virtual void detach(IObserver *) = 0; // 注销观察者
virtual void notify() = 0; // 通知观察者
virtual ~ISubject() {
}
};
// 具体主题
class ConcreteSubject: public ISubject {
public:
ConcreteSubject() {
m_percent = 13.0;
}
void setPrice(float price) {
m_percent = price;
}
void attach(IObserver *observer) {
m_observers.push_back(observer);
}
void detach(IObserver *observer) {
m_observers.remove(observer);
}
void notify() {
list<IObserver *>::iterator it = m_observers.begin();
while (it != m_observers.end()) {
(*it)->update(m_percent);
++it;
}
}
virtual ~ConcreteSubject() {
}
private:
list<IObserver *> m_observers; // 观察者列表
float m_percent; // 百分点
};
// 具体观察者
class ConcreteObserver: public IObserver {
public:
ConcreteObserver(string name) {
m_name = name;
}
void update(float percent) {
cout << m_name << " changes percent : " << percent << "\n";
}
virtual ~ConcreteObserver() {
}
private:
string m_name; // 名字
};
int main() {
// 创建主题、观察者
ConcreteSubject *pSubject = new ConcreteSubject();
IObserver *pObserver1 = new ConcreteObserver("Financial A");
IObserver *pObserver2 = new ConcreteObserver("Financial C");
// 注册观察者
pSubject->attach(pObserver1);
pSubject->attach(pObserver2);
// 更改价格,并通知观察者
pSubject->setPrice(18.5);
pSubject->notify();
// 注销观察者
cout << "========注销观察者========" << endl;
pSubject->detach(pObserver2);
// 再次更改状态,并通知观察者
pSubject->setPrice(11.0);
pSubject->notify();
delete pObserver1;
delete pObserver2;
delete pSubject;
return 0;
}
迭代器模式
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Iterator { // 迭代器抽象类
public:
virtual string frist() = 0;
virtual string next() = 0;
virtual bool isEnd() = 0;
virtual string currentItem() = 0;
virtual ~Iterator() {
}
};
class Aggregate { // 聚集抽象类
public:
virtual Iterator* createIterator() = 0;
virtual void push(string s) = 0;
virtual string pop(int index) = 0;
virtual int count() = 0;
virtual ~Aggregate() {
}
};
class ConcreteIterator: public Iterator { // 具体迭代器类
private:
Aggregate* aggregate;
int index;
public:
ConcreteIterator(Aggregate* a) {
index = 0;
aggregate = a;
}
~ConcreteIterator() {
if (aggregate) {
delete aggregate;
aggregate = nullptr;
}
index = 0;
}
string frist() {
return aggregate->pop(0);
}
string next() {
string str;
index++;
if (index < aggregate->count())
str = aggregate->pop(index);
return str;
}
bool isEnd() {
return (index >= aggregate->count());
}
string currentItem() {
return aggregate->pop(index);
}
};
class ConcreteAggregate: public Aggregate {
private:
vector<string> items;
Iterator* iterator;
public:
ConcreteAggregate() {
iterator = nullptr;
items.clear();
}
~ConcreteAggregate() {
if (iterator) {
delete iterator;
iterator = nullptr;
}
}
Iterator* createIterator() {
if (iterator == nullptr)
iterator = new ConcreteIterator(this);
return iterator;
}
int count() {
return items.size();
}
void push(string s) {
items.push_back(s);
}
string pop(int index) {
string str;
if (index < count())
str = items[index];
return str;
}
};
int main() {
ConcreteAggregate* ca = new ConcreteAggregate();
ca->push("Li Ming");
ca->push("Feng Yuan");
Iterator* it = new ConcreteIterator(ca);
while (!it->isEnd()) {
cout << it->currentItem() << endl;
it->next();
}
delete it;
delete ca;
return 0;
}
责任链模式
#include <iostream>
#include <vector>
using namespace std;
class Relatives {
public:
Relatives() {
}
virtual ~Relatives() {
}
virtual bool request(int)=0;
};
class Brother: public Relatives {
public:
Brother() {
}
virtual ~Brother() {
}
bool request(int num) {
if (num < 100) {
cout << "哥哥给你买" << endl;
return true;
} else {
cout << "哥哥不给买,让妈妈买吧" << endl;
return false;
}
}
};
class Mother: public Relatives {
public:
Mother() {
}
virtual ~Mother() {
}
bool request(int num) {
if (num < 500) {
cout << "妈妈给你买" << endl;
return true;
} else {
cout << "妈妈不给买,让爸爸买吧" << endl;
return false;
}
}
};
class Father: public Relatives {
public:
Father() {
}
virtual ~Father() {
}
bool request(int num) {
if (num < 1000) {
cout << "爸爸给你买" << endl;
return true;
} else {
cout << "太贵了,爸爸不给买" << endl;
return false;
}
}
};
class Buysomething {
private:
vector<Relatives*> p_vbuy;
public:
Buysomething() {
p_vbuy.push_back(new Brother);
p_vbuy.push_back(new Mother);
p_vbuy.push_back(new Father);
}
virtual ~Buysomething() {
p_vbuy.clear();
}
void request(int num) {
bool flag = false;
for (vector<Relatives*>::iterator it = p_vbuy.begin();
it != p_vbuy.end(); it++) {
flag = (*it)->request(num);
if (flag == true)
break;
}
}
};
int main() {
Buysomething *buy = new Buysomething;
buy->request(6000);
delete buy;
return 0;
}
命令模式
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define SAFE_DELETE(p) if (p) { delete p; p = NULL; }
/*烤肉师傅类,只负责烤串工作*/
class Barbecuer {
public:
void bakeMutton() {
cout << "Bake mutton" << endl;
}
void bakeChickenWing() {
cout << "Bake ChickenWing" << endl;
}
};
/*抽象命令类:是执行具体操作的接口*/
class Command {
public:
Command() {
}
virtual ~Command() {
}
Command(Barbecuer *receiver) :
p_receiver(receiver) {
}
virtual void executeCommand() = 0; //执行命令
protected:
Barbecuer *p_receiver;
};
/*具体命令类:烤羊肉串命令*/
class BakeMuttonCommand: public Command {
public:
BakeMuttonCommand(Barbecuer *receiver) {
p_receiver = receiver;
}
void executeCommand() {
p_receiver->bakeMutton();
}
};
/*具体命令类:烤鸡翅串命令*/
class BakeChickenWingCommand: public Command {
public:
BakeChickenWingCommand(Barbecuer *receiver) {
p_receiver = receiver;
}
void executeCommand() {
p_receiver->bakeChickenWing();
}
};
/*服务员类*/
class Waiter {
public:
void setOrder(Command *command);
void notify();
private:
vector<Command *> p_commandList; //这里相当于一个命令对象队列
};
void Waiter::setOrder(Command *command) {
p_commandList.push_back(command);
cout << "增加烤肉命令" << endl;
}
void Waiter::notify() {
vector<Command*>::iterator i;
for (i = p_commandList.begin(); i != p_commandList.end(); ++i)
(*i)->executeCommand();
}
int main(int argc, char *argv[]) {
//生成烤肉师傅、服务员、订单对象
Barbecuer *p_cook = new Barbecuer();
Command *p_mutton = new BakeMuttonCommand(p_cook);
Command *p_chickenwing = new BakeChickenWingCommand(p_cook);
Waiter *p_waiter = new Waiter();
//将订单对象推送到命令队列
p_waiter->setOrder(p_mutton);
p_waiter->setOrder(p_chickenwing);
//服务员通知烤肉师傅具体订单
p_waiter->notify();
SAFE_DELETE(p_cook);
SAFE_DELETE(p_mutton);
SAFE_DELETE(p_chickenwing);
SAFE_DELETE(p_waiter);
return 0;
}
备忘录模式
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//需保存的信息
class Memento {
public:
int m_vitality; //生命值
int m_attack; //进攻值
int m_defense; //防守值
public:
Memento(int vitality, int attack, int defense) :
m_vitality(vitality), m_attack(attack), m_defense(defense) {
}
Memento& operator=(const Memento &memento) {
m_vitality = memento.m_vitality;
m_attack = memento.m_attack;
m_defense = memento.m_defense;
return *this;
}
};
//游戏角色
class GameRole {
private:
int m_vitality;
int m_attack;
int m_defense;
public:
GameRole() :
m_vitality(100), m_attack(100), m_defense(100) {
}
Memento save() //保存进度,只与Memento对象交互,并不牵涉到Caretake
{
Memento memento(m_vitality, m_attack, m_defense);
return memento;
}
void load(Memento memento) //载入进度,只与Memento对象交互,并不牵涉到Caretake
{
m_vitality = memento.m_vitality;
m_attack = memento.m_attack;
m_defense = memento.m_defense;
}
void show() {
cout << "vitality : " << m_vitality << ", attack : " << m_attack
<< ", defense : " << m_defense << endl;
}
void attack() {
m_vitality -= 10;
m_attack -= 10;
m_defense -= 10;
}
};
//保存的进度库
class Caretake {
public:
Caretake() {
}
void save(Memento menento) {
m_vecMemento.push_back(menento);
}
Memento load(int state) {
return m_vecMemento[state];
}
private:
vector<Memento> m_vecMemento;
};
int main() {
Caretake caretake;
GameRole role;
cout << "初始值" << endl;
role.show(); //初始值
caretake.save(role.save()); //保存状态
cout << "进攻后" << endl;
role.attack();
role.show(); //进攻后
cout << "载入保存后的状态" << endl;
role.load(caretake.load(0)); //载入状态
role.show(); //恢复到状态0
return 0;
}
状态模式
#include <iostream>
#include <string>
using namespace std;
class Status {
public:
virtual void showStatus() = 0;
virtual ~Status() {
}
};
class HeatStatus: public Status {
public:
void showStatus() {
cout << "on heat status" << endl;
}
};
class NormalStatus: public Status {
public:
void showStatus() {
cout << "on normal status" << endl;
}
};
class CoolingStatus: public Status {
public:
void showStatus() {
cout << "on cooling status" << endl;
}
};
class StatusMgr {
private:
Status *p_status;
public:
void setStatus(Status *status) {
this->p_status = status;
}
void showCurStatus() {
p_status->showStatus();
}
virtual ~StatusMgr() {
if (p_status) {
delete p_status;
p_status = NULL;
}
}
};
int main() {
StatusMgr mStatusMgr;
NormalStatus mNormalStatus;
mStatusMgr.setStatus(&mNormalStatus);
mStatusMgr.showCurStatus();
HeatStatus mHeatStatus;
mStatusMgr.setStatus(&mHeatStatus);
mStatusMgr.showCurStatus();
CoolingStatus mCoolingStatus;
mStatusMgr.setStatus(&mCoolingStatus);
mStatusMgr.showCurStatus();
return 0;
}
访问者模式
#include <string>
#include <iostream>
#include <vector>
class Visitor
{
public:
Visitor(std::string s) { m_name = s; }
std::string getName() { return m_name; }
private:
std::string m_name;
};
class Receiver
{
public:
Receiver() {}
virtual bool accept(Visitor*) = 0;
std::string getName() { return s_name; }
protected:
bool m_free;
std::string s_name;
};
class ReceiverMan :public Receiver
{
public:
ReceiverMan(std::string s)
{
m_free = false;
s_name = s;
}
bool accept(Visitor* v)
{
if (!m_free)
{
std::cout << "ReceiverMan, Visitor name:" << v->getName() << std::endl;
m_free = true;
return true;
}
return false;
}
};
class ReceiverWoman :public Receiver
{
public:
ReceiverWoman(std::string s)
{
m_free = false;
s_name = s;
}
bool accept(Visitor* v)
{
if (!m_free)
{
std::cout << "ReceiverWoman, Visitor name:" << v->getName() << std::endl;
m_free = true;
return true;
}
return false;
}
};
class ReceiverMgr
{
public:
ReceiverMgr() {}
bool accept(Visitor* v)
{
bool flag = false ;
for (std::vector<Receiver*>::iterator it = vec_recv.begin();
it != vec_recv.end(); it++) {
flag = (*it)->accept(v);
if (flag == true){
return true;
}
}
std::cout << "Visit fail! visitor name:" << v->getName() << std::endl;
return false;
}
void addReceiver(Receiver* rv)
{
vec_recv.push_back(rv);
}
private:
std::vector<Receiver*> vec_recv;
};
int main() {
Visitor vr_Lee("Lee");
Visitor vr_John("John");
Visitor vr_Tom("Tom");
ReceiverMan rv_man("man");
ReceiverWoman rv_woman("woman");
ReceiverMgr rv_mgr;
rv_mgr.addReceiver(&rv_man);
rv_mgr.addReceiver(&rv_woman);
rv_mgr.accept(&vr_Lee);
rv_mgr.accept(&vr_John);
rv_mgr.accept(&vr_Tom);
std::cout << std::endl;
return 0;
}
中介者模式
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class Mediation;
//抽象人
class Person {
protected:
Mediation *m_Mediation; //中介
public:
virtual void setMediation(Mediation *mediation) {
} //设置中介
virtual void sendMessage(string message) {
} //向中介发送信息
virtual void getMessage(string message) {
} //从中介获取信息
virtual ~Person() {
}
};
//抽象中介机构
class Mediation {
public:
virtual void send(string message, Person *person) {
}
virtual void setA(Person *A) {
} //设置其中一方
virtual void setB(Person *B) {
}
virtual ~Mediation() {
}
};
//租房者
class Renter: public Person {
public:
void setMediation(Mediation *mediation) {
m_Mediation = Mediation;
}
void sendMessage(string message) {
m_Mediation->send(message, this);
}
void getMessage(string message) {
cout << "租房者收到信息" << message;
}
};
//房东
class Landlord: public Person {
public:
void setMediation(Mediation *Mediation) {
m_Mediation = Mediation;
}
void sendMessage(string message) {
m_Mediation->send(message, this);
}
void getMessage(string message) {
cout << "房东收到信息:" << message;
}
};
//房屋中介
class HouseMediation: public Mediation {
private:
Person *m_A; //租房者
Person *m_B; //房东
public:
HouseMediation() :
m_A(nullptr), m_B(nullptr) {
}
void setA(Person *A) {
m_A = A;
}
void setB(Person *B) {
m_B = B;
}
void send(string message, Person *person) {
if (person == m_A) //租房者给房东发信息
m_B->getMessage(message); //房东收到信息
else
m_A->getMessage(message);
}
};
int main() {
Mediation *mediation = new HouseMediation();
Person *person1 = new Renter(); //租房者
Person *person2 = new Landlord(); //房东
mediation->setA(person1);
mediation->setB(person2);
person1->setMediation(mediation);
person2->setMediation(mediation);
person1->sendMessage("我想在南京路附近租套房子,价格800元一个月\n");
person2->sendMessage("出租房子:南京路100号,70平米,1000元一个月\n");
delete person1;
delete person2;
delete mediation;
return 0;
}
解释器模式
#include <map>
#include <string>
#include<iostream>
using namespace std;
class Context {
private:
map<string, int> valueMap;
public:
void addValue(string key, int value) {
valueMap.insert(std::pair<string, int>(key, value));
}
int getValue(string key) {
return valueMap[key];
}
};
class AbstractExpression {
public:
virtual int interpreter(Context context) = 0;
};
class AddNonterminalExpression: public AbstractExpression {
private:
AbstractExpression *left;
AbstractExpression *right;
public:
AddNonterminalExpression(AbstractExpression *left,
AbstractExpression *right) {
this->left = left;
this->right = right;
}
int interpreter(Context context) {
return this->left->interpreter(context)
+ this->right->interpreter(context);
}
};
class SubtractNonterminalExpression: public AbstractExpression {
private:
AbstractExpression *left;
AbstractExpression *right;
public:
SubtractNonterminalExpression(AbstractExpression *left,
AbstractExpression *right) {
this->left = left;
this->right = right;
}
int interpreter(Context context) {
return this->left->interpreter(context)
- this->right->interpreter(context);
}
};
class TerminalExpression: public AbstractExpression {
private:
int i;
public:
TerminalExpression(int i) {
this->i = i;
}
int interpreter(Context context) {
return this->i;
}
};
int main() {
//a-b+c
cout << "解释器模式:a-b+c" << endl;
Context context;
context.addValue("a", 7);
context.addValue("b", 8);
context.addValue("c", 2);
SubtractNonterminalExpression *subtractValue =
new SubtractNonterminalExpression(
new TerminalExpression(context.getValue("a")),
new TerminalExpression(context.getValue("b")));
AddNonterminalExpression *addValue = new AddNonterminalExpression(
subtractValue, new TerminalExpression(context.getValue("c")));
cout << addValue->interpreter(context) << endl;
return 0;
}