fork download
  1. #include<map>
  2. #include<string>
  3. #include<iostream>
  4. using namespace std;
  5.  
  6. struct IFoo{};
  7.  
  8. struct Factory
  9. {
  10. struct Base{ virtual IFoo * build()const=0; };
  11.  
  12. typedef std::string Str;
  13. typedef std::map<const Str, Base*> Map;
  14. typedef Map::const_iterator It;
  15. typedef Map::value_type ValType;
  16.  
  17. template<class T> struct Builder : Base
  18. {
  19. IFoo* build()const { return new T; };
  20. };
  21.  
  22. template<class T> static void reg_class(const Str& key)
  23. {
  24. reg().insert( ValType(key, new Builder<T>()) );
  25. }
  26.  
  27. static IFoo* build(const Str& key)
  28. {
  29. It it = reg().find(key);
  30. return (it==reg().end())? 0l : it->second->build() ;
  31. }
  32. private:
  33. static std::map<const Str, Base*>& reg(){ static Map data; return data; }
  34.  
  35. };
  36.  
  37. struct Bar0 : IFoo
  38. {
  39. Bar0(){ cout<<"i am Bar0\n"; }
  40. };
  41. struct Bar1 : IFoo
  42. {
  43. Bar1(){ cout<<"i am Bar1\n"; }
  44. };
  45.  
  46. int main()
  47. {
  48. Factory::reg_class<Bar0>("Bar0");
  49. Factory::reg_class<Bar1>("Bar1");
  50.  
  51. //---------
  52.  
  53. IFoo* ptr = Factory::build("Bar0");
  54. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
i am Bar0