#ifndef SERVICE_FACTORY_H_
#define SERVICE_FACTORY_H_
#include <string>
#include <map>
#include <memory>
class Service {
public:
virtual void free() = 0;
};
typedef Service* (*CreationFunction)(void);
class Counter : public Service {
public:
static Service* create() { return new Counter(); }
void free() { delete this; }
};
class ServiceFactory {
public:
~ServiceFactory() {
_registeredServices.clear();
}
static ServiceFactory* getInstance() {
static ServiceFactory instance;
return &instance;
}
void registerService(const std::string &serviceName, CreationFunction fn) {
_registeredServices[serviceName] = fn;
}
Service* createService(const std::string &serviceName) {
auto it = _registeredServices.find(serviceName);
if(it != _registeredServices.end())
return it->second();
return NULL;
}
private:
ServiceFactory() {
registerService("COUNTER", &Counter::create);
}
ServiceFactory(const ServiceFactory&) { /* Nothing implemented yet */ }
ServiceFactory& operator=(const ServiceFactory&) { return *this; }
std::map<std::string, CreationFunction> _registeredServices;
};
#endif // SERVICE_FACTORY_H_
#include <iostream>
int main() {
Service* counter = ServiceFactory::getInstance()->createService("COUNTER");
if(counter) {
std::cout << "Counter was made." << std::endl;
counter->free();
} else {
std::cout << "Counter was not made." << std::endl;
}
return 0;
}