abstractfactory.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #pragma once
  2. #include <iostream>
  3. #include <string>
  4. #include <map>
  5. template <class Base, typename CreatorParam>
  6. class AbstractCreator {
  7. public:
  8. virtual ~AbstractCreator() {}
  9. virtual Base* create(const CreatorParam &id) const = 0;
  10. };
  11. template <class ObjectClass, class Base, typename CreatorParam>
  12. class Creator : public AbstractCreator<Base, CreatorParam> {
  13. public:
  14. Creator() {}
  15. virtual ~Creator() {}
  16. Base* create(const CreatorParam &params) const {
  17. return dynamic_cast<Base*>(new ObjectClass(params));
  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 CreatorParam>
  33. void addClass(const IdType &id) {
  34. registerClass(id, new Creator<C, Base, CreatorParam>());
  35. }
  36. template <typename CreatorParam>
  37. Base* createObject(const IdType &idClass, const CreatorParam &parameters) {
  38. return factory_[idClass]->create(parameters);
  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. };