#include <iostream>
#include <string>
#include <vector>
using namespace std;
class fly_weight
{
public:
virtual ~fly_weight(){}
virtual void operation(const string &state){}
string get_state()
{
return _state;
}
protected:
fly_weight(const string &state):_state(state){}
private:
string _state;
};
class concrete_fly_weight : public fly_weight
{
public:
concrete_fly_weight(const string &state):fly_weight(state){}
void operation(const string &state)
{
cout<<"[inside]: "<< get_state() <<" [outside]: "<<state<<endl;
}
};
class fly_weight_factory
{
public:
fly_weight *get_fly_weight(const string &state)
{
vector<fly_weight*>::iterator it = flys.begin();
for (; it != flys.end(); ++it)
{
if ((*it)->get_state() == state)
{
return *it;
}
}
fly_weight *new_fly = new concrete_fly_weight(state);
flys.push_back(new_fly);
return new_fly;
}
private:
vector<fly_weight*> flys;
};
int main()
{
fly_weight_factory *factory = new fly_weight_factory();
fly_weight *f1 = factory->get_fly_weight("fly_weight 1");
fly_weight *f2 = factory->get_fly_weight("fly_weight 2");
fly_weight *f3 = factory->get_fly_weight("fly_weight 3");
fly_weight *f4 = factory->get_fly_weight("fly_weight 4");
fly_weight *f5 = factory->get_fly_weight("fly_weight 1");
cout<< f1->get_state() <<endl;
cout<< f2->get_state() <<endl;
cout<< f3->get_state() <<endl;
cout<< f4->get_state() <<endl;
cout<< f5->get_state() <<endl;
return 0;
}
///
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class user
{
public:
user(const string &name):_name(name){}
string name()const { return _name; }
private:
string _name;
};
class web_set
{
public:
virtual ~web_set(){}
virtual void use(const user &u) =0;
virtual string name()=0;
};
class concrete_web_set : public web_set
{
public:
concrete_web_set(const string &name):_name(name){}
void use(const user &usr)
{
cout<<"web: "<<_name<<" [user]: "<<usr.name()<<endl;
}
string name(){ return _name; }
private:
string _name;
};
class factory
{
public:
web_set *get_fly_weight(const string &name)
{
vector<web_set*>::iterator it = flys.begin();
for (; it != flys.end(); ++it)
{
if ((*it)->name() == name)
{
return *it;
}
}
web_set *new_fly = new concrete_web_set(name);
flys.push_back(new_fly);
return new_fly;
}
private:
vector<web_set*> flys;
};
int main()
{
factory *fact = new factory();
user u1("U1");
user u2("U2");
web_set *f1 = fact->get_fly_weight("nea");
web_set *f2 = fact->get_fly_weight("sina");
f1->use(u1);
f1->use(u2);
f2->use(u1);
f2->use(u2);
return 0;
}