abstractfactory.h 1.5 KB

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