迭代器模式
GOOD:提供一种方法顺序访问一个聚敛对象的各个元素,而又不暴露该对象的内部表示。
为遍历不同的聚集结构提供如开始,下一个,是否结束,当前一项等统一接口。
例:
#include <iostream>
#include <vector>
using namespace std;
template<class Item>
class Iterator
{
public:
virtual void first()=0;
virtual void next()=0;
virtual Item* currentItem()=0;
virtual bool isDone()=0;
virtual ~Iterator(){}
};
template<class Item>
class ConcreteAggregate;
template<class Item>
class ConcreteIterator : public Iterator <Item>
{
ConcreteAggregate<Item> * aggr;
int cur;
public:
ConcreteIterator(ConcreteAggregate<Item>*a):aggr(a),cur(0){}
virtual void first()
{
cur=0;
}
virtual void next()
{
if(cur<aggr->getLen())
cur++;
}
virtual Item* currentItem()
{
if(cur<aggr->getLen())
return &(*aggr)[cur];
else
return NULL;
}
virtual bool isDone()
{
return (cur>=aggr->getLen());
}
};
template<class Item>
class Aggregate
{
public:
virtual Iterator<Item>* createIterator()=0;
virtual ~Aggregate(){}
};
template<class Item>
class ConcreteAggregate:public Aggregate<Item>
{
vector<Item >data;
public:
ConcreteAggregate()
{
data.push_back(1);
data.push_back(2);
data.push_back(3);
}
virtual Iterator<Item>* createIterator()
{
return new ConcreteIterator<Item>(this);
}
Item& operator[](int index)
{
return data[index];
}
int getLen()
{
return data.size();
}
};
int main()
{
Aggregate<int> * aggr =new ConcreteAggregate<int>();
Iterator<int> *it=aggr->createIterator();
for(it->first();!it->isDone();it->next())
{
cout<<*(it->currentItem())<<endl;
}
delete it;
delete aggr;
return 0;
}
单例模式
GOOD:保证一个类仅有一个实例,并提供一个访问它的全局访问点
例:
#include<iostream>
#include<string>
#include<vector>
using namespacestd;
class Singelton
{
private:
Singelton(){}
static Singelton* singel;
public:
static Singelton* GetInstance()
{
if(singel == NULL)
{
singel = new Singelton();
}
return singel;
}
};
Singelton* Singelton::singel =NULL;//注意静态变量类外初始化
客户端:
int main()
{
Singelton* s1=Singelton::GetInstance();
Singelton* s2=Singelton::GetInstance();
if(s1 == s2)
cout<<"ok"<<endl;
else
cout<<"no"<<endl;
return 0;
}
桥接模式
GOOD:将抽象部分与实现部分分离,使它们可以独立变化。
这里说的意思不是让抽象基类与具体类分离,而是现实系统可能有多角度分类,每一种分类都有可能变化,那么把这种多角度分离出来让它们独立变化,减少它们之间的耦合性,即如果继承不能实现“开放-封闭原则”的话,就应该考虑用桥接模式。如下例:让“手机”既可以按品牌分类也可以
例:
#include<iostream>
#include<string>
#include<vector>
using namespacestd;
//手机软件
classHandsetSoft
{
public:
virtual void Run()=0;
};
//游戏软件
classHandsetGame : public HandsetSoft
{
public:
virtual void Run()
{
cout<<"运行手机游戏"<<endl;
}
};
//通讯录软件
classHandSetAddressList : public HandsetSoft
{
public:
virtual void Run()
{
cout<<"手机通讯录"<<endl;
}
};
//手机品牌
classHandsetBrand
{
protected:
HandsetSoft* m_soft;
public:
void SetHandsetSoft(HandsetSoft* temp)
{
m_soft = temp;
}
virtual void Run()=0;
};
//M品牌
classHandsetBrandM : public HandsetBrand
{
public:
virtual void Run()
{
m_soft->Run();
}
};
//N品牌
classHandsetBrandN : public HandsetBrand
{
public:
virtual void Run()
{
m_soft->Run();
}
};
//客户端
int main()
{
HandsetBrand *brand;
brand = new HandsetBrandM();
brand->SetHandsetSoft(newHandsetGame());
brand->Run();
brand->SetHandsetSoft(newHandSetAddressList());
brand->Run();
return 0;
}
命令模式
GOOD:一、建立命令队列;二、可以将命令记入日志;三、接收请求的一方可以拒绝;四、添加一个新命令类不影响其它类;
命令模式把请求一个操作的对象与知道怎么操行一个操作的对象分开
例:
#include<iostream>
#include<string>
#include<vector>
using namespacestd;
//烤肉师傅
class Barbucer
{
public:
void MakeMutton()
{
cout<<"烤羊肉"<<endl;
}
void MakeChickenWing()
{
cout<<"烤鸡翅膀"<<endl;
}
};
//抽象命令类
class Command
{
protected:
Barbucer* receiver;
public:
Command(Barbucer* temp)
{
receiver = temp;
}
virtual void ExecuteCmd()=0;
};
//烤羊肉命令
classBakeMuttonCmd : public Command
{
public:
BakeMuttonCmd(Barbucer* temp) :Command(temp){}
virtual void ExecuteCmd()
{
receiver->MakeMutton();
}
};
//烤鸡翅
classChickenWingCmd : public Command
{
public:
ChickenWingCmd(Barbucer* temp) :Command(temp){}
virtual void ExecuteCmd()
{
receiver->MakeChickenWing();
}
};
//服务员类
class Waiter
{
protected:
vector<Command*> m_commandList;
public:
void SetCmd(Command* temp)
{
m_commandList.push_back(temp);
cout<<"增加定单"<<endl;
}
//通知执行
void Notify()
{
vector<Command*>::iteratorp=m_commandList.begin();
while(p!=m_commandList.end())
{
(*p)->ExecuteCmd();
p++;
}
}
};
//客户端
int main()
{
//店里添加烤肉师傅、菜单、服务员等顾客
Barbucer* barbucer=new Barbucer();
Command* cmd= newBakeMuttonCmd(barbucer);
Command* cmd2=newChickenWingCmd(barbucer);
Waiter* girl = new Waiter();
//点菜
girl->SetCmd(cmd);
girl->SetCmd(cmd2);
//服务员通知
girl->Notify();
return 0;
}
责任链模式
GOOD:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理为止。
例:
#include<iostream>
#include<string>
#include<vector>
using namespacestd;
//请求
class Request
{
public:
string m_strContent;
int m_nNumber;
};
//管理者
class Manager
{
protected:
Manager* manager;
string name;
public:
Manager(string temp)
{
name = temp;
}
voidSetSuccessor(Manager* temp)
{
manager =temp;
}
virtual void GetRequest(Request* request)= 0;
};
//经理
classCommonManager : public Manager
{
public:
CommonManager(string strTemp) :Manager(strTemp){}
virtual voidGetRequest(Request* request)
{
if (request->m_nNumber>=0 && request->m_nNumber<10 )
{
cout<<name<<"处理了"<<request->m_nNumber<<"个请求"<<endl;
}
else
{
manager->GetRequest(request);
}
}
};
//总监
class MajorDomo: public Manager
{
public:
MajorDomo(string name) : Manager(name){}
virtual void GetRequest(Request* request)
{
if(request->m_nNumber>=10)
{
cout<<name<<"处理了"<<request->m_nNumber<<"个请求"<<endl;
}
}
};
//客户端
int main()
{
Manager * common = newCommonManager("张经理");
Manager * major = new MajorDomo("李总监");
common->SetSuccessor(major);
Request* req = new Request();
req->m_nNumber = 33;
common->GetRequest(req);
req->m_nNumber = 3;
common->GetRequest(req);
return 0;
}
中介者模式
GOOD:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显示的相互引用,从而降低耦合;而且可以独立地改变它们之间的交互。
例:
#include <iostream>
#include<string>
#include<vector>
using namespacestd;
class Colleague;
//中介者类
class Mediator
{
public:
virtual void Send(stringmessage,Colleague* col) = 0;
};
//抽象同事类
class Colleague
{
protected:
Mediator* mediator;
public:
Colleague(Mediator* temp)
{
mediator = temp;
}
};
//同事一
class Colleague1: public Colleague
{
public:
Colleague1(Mediator* media) :Colleague(media){}
void Send(string strMessage)
{
mediator->Send(strMessage,this);
}
void Notify(string strMessage)
{
cout<<"同事一获得了消息"<<strMessage<<endl;
}
};
//同事二
class Colleague2: public Colleague
{
public:
Colleague2(Mediator* media) :Colleague(media){}
void Send(string strMessage)
{
mediator->Send(strMessage,this);
}
void Notify(string strMessage)
{
cout<<"同事二获得了消息"<<strMessage<<endl;
}
};
//具体中介者类
classConcreteMediator : public Mediator
{
public:
Colleague1 * col1;
Colleague2 * col2;
virtual void Send(stringmessage,Colleague* col)
{
if(col == col1)
col2->Notify(message);
else
col1->Notify(message);
}
};
//客户端:
int main()
{
ConcreteMediator * m = newConcreteMediator();
//让同事认识中介
Colleague1* col1 = new Colleague1(m);
Colleague2* col2 = new Colleague2(m);
//让中介认识具体的同事类
m->col1 = col1;
m->col2 = col2;
col1->Send("吃饭了吗?");
col2->Send("还没吃,你请吗?");
return 0;
}
享元模式
GOOD:运用共享技术有效地支持大量细粒度的对象(对于C++来说就是共用一个内存块啦,对象指针指向同一个地方)。
如果一个应用程序使用了大量的对象,而这些对象造成了很大的存储开销就应该考虑使用。
还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用较少的共享对象取代多组对象,此时可以考虑使用享元。
例:
#include<iostream>
#include<string>
#include<vector>
using namespacestd;
//抽象的网站
class WebSite
{
public:
virtual void Use()=0;
};
//具体的共享网站
classConcreteWebSite : public WebSite
{
private:
string name;
public:
ConcreteWebSite(string strName)
{
name = strName;
}
virtual void Use()
{
cout<<"网站分类:"<<name<<endl;
}
};
//不共享的网站
classUnShareWebSite : public WebSite
{
private:
string name;
public:
UnShareWebSite(string strName)
{
name = strName;
}
virtual void Use()
{
cout<<"不共享的网站:"<<name<<endl;
}
};
//网站工厂类,用于存放共享的WebSite对象
class WebFactory
{
private:
vector<WebSite*>websites;
public:
WebSite* GetWeb()
{
vector<WebSite*>::iteratorp = websites.begin();
return *p;
}
WebFactory()
{
websites.push_back(newConcreteWebSite("测试"));
}
};
//客户端
int main()
{
WebFactory* f= new WebFactory();
WebSite* ws= f->GetWeb();
ws->Use();
WebSite* ws2 = f->GetWeb();
ws2->Use();
//不共享的类
WebSite* ws3 = new UnShareWebSite("测试");
ws3->Use();
return 0;
}
解释器模式
GOOD:通常当一个语言需要解释执行,并且你可以将该语言中的句子表示成为一个抽象的语法树时,可以使用解释器模式。
例:
#include<iostream>
#include<string>
#include<vector>
using namespacestd;
class Context;
classAbstractExpression
{
public:
virtual void Interpret(Context*context)=0;
};
class Expression: public AbstractExpression
{
public:
virtual void Interpret(Context* context)
{
cout<<"终端解释器"<<endl;
};
};
classNonterminalExpression : public AbstractExpression
{
public:
virtual void Interpret(Context* context)
{
cout<<"非终端解释器"<<endl;
}
};
class Context
{
public:
string input;
string output;
};
//客户端
int main()
{
Context* context = new Context();
vector<AbstractExpression*>express;
express.push_back(new Expression());
express.push_back(newNonterminalExpression());
express.push_back(newNonterminalExpression());
vector<AbstractExpression*>::iteratorp = express.begin();
while (p!= express.end())
{
(*p)->Interpret(context);
p++;
}
return 0;
}
访问者模式
GOOD:适用于数据结构稳定的系统。它把数据结构和作用于数据结构上的操作分离开,使得操作集合
优点:新增加操作很容易,因为增加新操作就相当于增加一个访问者,访问者模式将有关的行为集中到一个访问者对象中
例:
#include<iostream>
#include<string>
#include<vector>
using namespacestd;
class Man;
class Woman;
//行为
class Action
{
public:
virtual void GetManConclusion(Man*concreteElementA)=0;
virtual void GetWomanConclusion(Woman*concreteElementB)=0;
};
//成功
class Success :public Action
{
public:
virtual void GetManConclusion(Man*concreteElementA)
{
cout<<"男人成功时,背后有个伟大的女人"<<endl;
}
virtual void GetWomanConclusion(Woman*concreteElementB)
{
cout<<"女人成功时,背后有个没用的男人"<<endl;
}
};
//失败
class Failure :public Action
{
public:
virtual void GetManConclusion(Man*concreteElementA)
{
cout<<"男人失败时,背后有个伟大的女人"<<endl;
}
virtual void GetWomanConclusion(Woman*concreteElementB)
{
cout<<"女人失败时,背后有个没用的男人"<<endl;
}
};
//抽象人类
class Person
{
public:
virtual void Accept(Action* visitor)=0;
};
//男人
class Man :public Person
{
public:
virtual void Accept(Action* visitor)
{
visitor->GetManConclusion(this);
}
};
//女人
class Woman :public Person
{
public:
virtual void Accept(Action* visitor)
{
visitor->GetWomanConclusion(this);
}
};
//对象结构类
class ObjectStructure
{
private:
vector<Person*>m_personList;
public:
void Add(Person*p)
{
m_personList.push_back(p);
}
voidDisplay(Action* a)
{
vector<Person*>::iteratorp = m_personList.begin();
while (p!=m_personList.end())
{
(*p)->Accept(a);
p++;
}
}
};
//客户端
int main()
{
ObjectStructure * os= newObjectStructure();
os->Add(new Man());
os->Add(new Woman());
Success* success = new Success();
os->Display(success);
Failure* fl = new Failure();
os->Display(fl);
return 0;
}