Glock 17Pro | pour le plaisir et ça pourra servir à d'autre :
Code :
- template <class ManufacturedType, typename ClassIDKey=std::string>
- class GenericFactory
- {
- public:
- typedef std::auto_ptr<ManufacturedType> (*BaseCreateFn)();
- typedef std::map<ClassIDKey, BaseCreateFn> FnRegistry;
- FnRegistry registry;
- public:
- static GenericFactory &instance(){ static GenericFactory bf; return bf; }
- void RegCreateFn(const ClassIDKey &, BaseCreateFn);
- std::auto_ptr<ManufacturedType> Create(const ClassIDKey &className) const;
- };
- ///////////////////////////////
- template <class ManufacturedType, typename ClassIDKey>
- void GenericFactory<ManufacturedType,ClassIDKey>::RegCreateFn(const ClassIDKey & className, BaseCreateFn fn)
- {
- registry[className] = fn;
- }
- ///////////////////////////////
- template <class ManufacturedType, typename ClassIDKey>
- std::auto_ptr<ManufacturedType> GenericFactory<ManufacturedType,ClassIDKey>::Create(const ClassIDKey &className) const
- {
- std::auto_ptr<ManufacturedType> theObject(0);
- FnRegistry::const_iterator regEntry = registry.find(className);
- if (regEntry != registry.end())
- {
- theObject= regEntry->second();
- }
- return theObject;
- }
- template <class AncestorType, class ManufacturedType, typename ClassIDKey=std::string>
- class RegisterInFactory
- {
- public:
- static std::auto_ptr<AncestorType> CreateInstance()
- {
- return std::auto_ptr<AncestorType>(new ManufacturedType);
- }
- RegisterInFactory(const ClassIDKey &id)
- {
- GenericFactory<AncestorType>::instance().RegCreateFn(id, CreateInstance);
- }
- };
- struct Figure
- {virtual void SeDessiner(){cout<<"Je suis une Figure"<<endl;}};
- struct Carre : public Figure
- {void SeDessiner(){cout<<"Je suis un Carre"<<endl;}};
- struct Voiture
- {virtual void SeDessiner(){cout<<"Je suis une Voiture"<<endl;}};
- struct Ferrari : public Voiture
- { void SeDessiner(){cout<<"Je suis une Ferrari"<<endl;}};
- int main()
- {
- RegisterInFactory<Voiture, Voiture> registerMe("Voiture" );
- RegisterInFactory<Voiture, Ferrari> registerMe2("Ferrari" );
- RegisterInFactory<Figure, Carre> registerMe3("Carre" );
- GenericFactory<Voiture>::instance().Create("Voiture" )->SeDessiner();
- GenericFactory<Figure>::instance().Create("Carre" )->SeDessiner();
- GenericFactory<Voiture>::instance().Create("Ferrari" )->SeDessiner();
- system("pause" );
- }
|
|