fork download
  1. #ifndef SERVICE_FACTORY_H_
  2. #define SERVICE_FACTORY_H_
  3.  
  4. #include <string>
  5. #include <map>
  6. #include <memory>
  7.  
  8. class Service {
  9. public:
  10. virtual void free() = 0;
  11. };
  12.  
  13. typedef Service* (*CreationFunction)(void);
  14.  
  15. class Counter : public Service {
  16. public:
  17. static Service* create() { return new Counter(); }
  18. void free() { delete this; }
  19. };
  20.  
  21. class ServiceFactory {
  22. public:
  23. ~ServiceFactory() {
  24. _registeredServices.clear();
  25. }
  26.  
  27. static ServiceFactory* getInstance() {
  28. static ServiceFactory instance;
  29. return &instance;
  30. }
  31.  
  32. void registerService(const std::string &serviceName, CreationFunction fn) {
  33. _registeredServices[serviceName] = fn;
  34. }
  35.  
  36. Service* createService(const std::string &serviceName) {
  37. auto it = _registeredServices.find(serviceName);
  38. if(it != _registeredServices.end())
  39. return it->second();
  40. return NULL;
  41. }
  42. private:
  43. ServiceFactory() {
  44. registerService("COUNTER", &Counter::create);
  45. }
  46.  
  47. ServiceFactory(const ServiceFactory&) { /* Nothing implemented yet */ }
  48.  
  49. ServiceFactory& operator=(const ServiceFactory&) { return *this; }
  50.  
  51. std::map<std::string, CreationFunction> _registeredServices;
  52. };
  53.  
  54. #endif // SERVICE_FACTORY_H_
  55.  
  56. #include <iostream>
  57.  
  58. int main() {
  59. Service* counter = ServiceFactory::getInstance()->createService("COUNTER");
  60. if(counter) {
  61. std::cout << "Counter was made." << std::endl;
  62. counter->free();
  63. } else {
  64. std::cout << "Counter was not made." << std::endl;
  65. }
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Counter was made.