享元模式,就是共享某些对象,如string中的隐式共享。
/*
**假设一篇文章有标题与内容两个属性,我们转载文章时,就没有必要再创建一个文章对象。
**或者当我们创建一篇已经存在的文章时,也没有必要创建一个新的文章对象。
**此时,可以采用Flyweight享元模式
**但是又必须表现出某些不同的特性,如一篇文章可以有不同的访问者
*/
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
//文章类
class Article
{
private:
//标题与标题
string title;
string content;
public:
Article(char *t,char *c):title(t),content(c){}
//判断是否相等
bool equals(const char*t,const char *c)
{
if( strcmp(title.c_str(),t)==0 && strcmp(content.c_str(),c)==0 )
return true;
return false;
}
void printArticle()
{
cout<<"标题:"<<title.c_str()<<endl<<"内容:"<<content.c_str()<<endl;
}
};
//享元类
class Flyweight
{
public:
virtual ~Flyweight(){}
virtual void visit(char *visitor)=0;
virtual bool isEquals(const char *c,const char *t)=0;
private:
};
//class
class ConcreteFlyweight:public Flyweight
{
public:
ConcreteFlyweight(char *c,char *t):article(c,t){}
void visit(char *visitor)
{
cout<<"访问者:"<<visitor<<endl;
article.printArticle();
cout<<endl;
}
bool isEquals(const char *c,const char *t)
{
return article.equals(c,t);
}
private:
Article article;
};
class FlyweightFactory
{
public:
//如果没有此文章对象,则先创建,在返回。
Flyweight* getFlyweight(char *c,char *t)
{
for(vector<Flyweight*>::iterator iter=vf.begin();iter!=vf.end();iter++)
{
if((*iter)->isEquals(c,t))
return *iter;
}
Flyweight *f=new ConcreteFlyweight(c,t);
vf.push_back(f);
return f;
}
//返回共享对象的个数
int FlyweightCount()
{
return vf.size();
}
~FlyweightFactory()
{
for(vector<Flyweight*>::iterator iter=vf.begin();iter!=vf.end();iter++)
delete *iter;
}
private:
vector<Flyweight*> vf;
};
int main()
{
FlyweightFactory *ff=new FlyweightFactory();
Flyweight *f1=ff->getFlyweight("我们毕业了","我们将在2013年毕业");
f1->visit("chen");
cout<<"共有共享文章 "<<ff->FlyweightCount()<<" 篇"<<endl;
Flyweight *f2=ff->getFlyweight("学习设计模式","我们正在学习设计模式");
f2->visit("chen");
cout<<"共有共享文章 "<<ff->FlyweightCount()<<" 篇"<<endl;
Flyweight *f3=ff->getFlyweight("我们毕业了","我们将在2013年毕业");
f3->visit("xxx");
cout<<"共有共享文章 "<<ff->FlyweightCount()<<" 篇"<<endl;
delete ff;
return 0;
}