Template Factory


/ Published in: C++
Save to your folder(s)

template factory in modern c++ design


Copy this code and paste it in your HTML
  1. template
  2. <
  3. class AbstractProduct,
  4. typename IdentifierType,
  5. typename ProductCreator = std::function<AbstractProduct* ( void)>
  6. >
  7. class Factory
  8. {
  9. public:
  10. bool Register(const IdentifierType& id, ProductCreator creator)
  11. {
  12. associations_.insert(
  13. AssocMap::value_type(id, creator));
  14. return true ;
  15. }
  16. AbstractProduct* CreateObject( const IdentifierType& id)
  17. {
  18. typename AssocMap::const_iterator i =
  19. associations_.find(id);
  20. if (i != associations_.end())
  21. {
  22. return ((*i).second)();
  23. }
  24.  
  25. return NULL;
  26. }
  27.  
  28. private:
  29. typedef map<IdentifierType, ProductCreator> AssocMap;
  30. AssocMap associations_;
  31. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.