1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
#include <map>
#include <iostream>
#include <iterator>
using namespace std;
class Figure
{
public:
// static bool val;
//static Figure* Create();
virtual void SeDessiner(void)=0;
};
//bool Figure::val = false;
class Cercle : public Figure {
public:
static bool val;
virtual void SeDessiner(){cout<<"Je suis un cercle"<<endl;}
static Figure* Create(){
return new Cercle();
}
};
class Carre : public Figure {
public:
static bool val;
virtual void SeDessiner(){cout<<"Je suis carre"<<endl;}
static Figure* Create(){
return new Carre();
}
};
template<typename Key,typename Object> class Factory
{
private:
typedef Object* (*Creator)();
static Factory<Key,Object>* m_fact;
map<Key, Creator> m_list;
Factory(){}
~Factory(){}
public:
static Factory* GetInstance()
{
if(m_fact==NULL)
{
m_fact = new Factory;
}
return m_fact;
}
static void Kill()
{
if(m_fact!=NULL)
{
delete m_fact;
}
}
bool Register(Key key,Creator creator)
{
bool ret=true;
if(m_list.find(key)!=m_list.end())
{
ret=false;
}
else
{
m_list[key]=creator;
}
return ret;
}
Object* create(Key key)
{
Object *obj=NULL;
Creator crt;
std::map<Key, Creator>::iterator it; //ca casse ici
it=m_list.find(key);
if(it!=m_list.end())
{
crt=(*it).second;
obj=crt();
}
return obj;
}
};
template<typename Key,typename Object> Factory<Key,Object>* Factory<Key,Object>::m_fact=NULL;
bool Carre::val= Factory<string,Figure>::GetInstance()->Register("Carre",Carre::Create);
bool Cercle::val=Factory<string,Figure>::GetInstance()->Register("Cercle",Cercle::Create);
int main(void)
{
Figure *c=Factory<string,Figure>::GetInstance()->create("Cercle");
Figure *ca=Factory<string,Figure>::GetInstance()->create("Carre");
c->SeDessiner();
ca->SeDessiner();
delete c;
delete ca;
return 0;
} |
Partager