AbstractFactory.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #pragma once
  2. #include <iostream>
  3. #include <string>
  4. #include <map>
  5. template <class Base, typename IdType>
  6. class AbstractCreator {
  7. public:
  8. virtual ~AbstractCreator() {}
  9. virtual Base* create(const IdType &id) const = 0;
  10. };
  11. template <class ObjectClass, class Base, typename IdType>
  12. class Creator : public AbstractCreator <Base, IdType> {
  13. public:
  14. Creator(IdType id) {}
  15. virtual ~Creator() {}
  16. Base* create(const IdType &id) const {
  17. return dynamic_cast<Base*>(new ObjectClass(id));
  18. }
  19. };
  20. template <class Base, class IdType>
  21. class ObjectFactory {
  22. protected:
  23. typedef AbstractCreator<Base, IdType> AbstractFactory;
  24. typedef std::map<IdType, AbstractFactory*> FactoryMap;
  25. FactoryMap factory_;
  26. public:
  27. ObjectFactory() {}
  28. virtual ~ObjectFactory() {
  29. for (auto& item : factory_)
  30. delete item.second;
  31. }
  32. template <class C, typename idCreator>
  33. void add(const IdType &id) {
  34. registerClass(id, new Creator<C, Base, idCreator>(id));
  35. }
  36. template <typename idCreator>
  37. Base* create(const IdType &idClass, const idCreator &id) {
  38. return factory_[idClass]->create(id);
  39. }
  40. protected:
  41. void registerClass(const IdType &id, AbstractFactory *ConcreteFabric) {
  42. typename FactoryMap::iterator it = factory_.find(id);
  43. if (it == factory_.end())
  44. factory_[id] = ConcreteFabric;
  45. else
  46. delete ConcreteFabric;
  47. }
  48. };