fork download
  1. #include <string>
  2. #include <map>
  3. #include <iostream>
  4.  
  5. class Whatever {
  6. public:
  7. // контракт
  8. virtual void foo() = 0;
  9. };
  10.  
  11. class WhateverFactory {
  12. public:
  13. typedef Whatever* (*WhateverCtor)();
  14.  
  15. static void registerClass(const std::string &name, WhateverCtor ctor) {
  16. if ( m_plugins.find(name) == m_plugins.end() ) {
  17. m_plugins[name] = ctor;
  18. }
  19. }
  20.  
  21. static bool isRegistered(const std::string &cls) {
  22. return m_plugins.find(cls) != m_plugins.end();
  23. }
  24.  
  25. static Whatever* createInstanceOf(const std::string &name) {
  26. std::map<std::string, WhateverCtor>::iterator ctor;
  27. if ( (ctor = m_plugins.find(name)) != m_plugins.end() ) {
  28. return ctor->second();
  29. } else {
  30. return NULL;
  31. }
  32. }
  33.  
  34. private:
  35. WhateverFactory() {}
  36.  
  37. static std::map<std::string, WhateverCtor> m_plugins;
  38. };
  39.  
  40. std::map<std::string, WhateverFactory::WhateverCtor> WhateverFactory::m_plugins;
  41.  
  42. class HelloWorld : public Whatever {
  43. public:
  44. HelloWorld() : m_message("Hello, World!") {}
  45.  
  46. void foo() {
  47. std::cout << m_message << std::endl;
  48. }
  49.  
  50. static HelloWorld* create() {
  51. return new HelloWorld;
  52. }
  53.  
  54. private:
  55. std::string m_message;
  56. };
  57.  
  58. void load() {
  59. WhateverFactory::registerClass("HelloWorld", reinterpret_cast<WhateverFactory::WhateverCtor>(HelloWorld::create));
  60. }
  61.  
  62. int main() {
  63. load();
  64. Whatever *w = WhateverFactory::createInstanceOf("HelloWorld");
  65. if ( w ) {
  66. w->foo();
  67. }
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0.02s 2860KB
stdin
Standard input is empty
stdout
Hello, World!