当前位置:   article > 正文

工厂模式boost::factory_boost::factory

boost::factory>()
  1. #ifndef MP_OBJECT_FACTORY_H
  2. #define MP_OBJECT_FACTORY_H
  3. #include <boost/function.hpp>
  4. #include <map>
  5. typedef boost::shared_ptr<Product> Product_ptr;
  6. /// 工厂模式泛型实现.
  7. /// 限制: 生成的对象必须为通过默认构造函数来构造.
  8. /// 当然你也可以扩展这个模板让它支持更多参数的构造函数.
  9. template<typename IdType, typename ObjectType>
  10. class ObjectFactory
  11. {
  12. public:
  13. /// 表示默认构造函数的函数对象.
  14. typedef boost::function< ObjectType* () > CreatorType;
  15. /// 构造函数对应的函数对象的关联容器.
  16. typedef std::map<IdType, CreatorType> ObjectCreator_map;
  17. /// 注册子类对象的构造函数信息.
  18. void RegisterObjectCreator(const IdType& id, const CreatorType &creator)
  19. {
  20. objectCreatorMap_[id] = creator;
  21. }
  22. /// 通过默认构造函数在堆上创建一个新的对象实例. 使用new生成.
  23. ObjectType * MakeObject(const IdType& id)
  24. {
  25. ObjectCreator_map::const_iterator iter = objectCreatorMap_.find(id);
  26. if (iter == objectCreatorMap_.end())
  27. {
  28. return NULL;
  29. }
  30. else
  31. {
  32. return (iter->second)();
  33. }
  34. }
  35. private:
  36. ObjectCreator_map objectCreatorMap_;
  37. };
  38. #endif
  39. #include "Product.h"
  40. #include "ConcreteProductA.h"
  41. #include "ConcreteProductB.h"
  42. #include "ObjectFactory.h"
  43. #include <string>
  44. #include <boost/functional/factory.hpp>
  45. int main(int argc, char **argv)
  46. {
  47. ObjectFactory<std::string, Product> productFactory; // 对象工厂
  48. // 注册对象构造器.
  49. productFactory.RegisterObjectCreator("PRODUCT_A", boost::factory<ConcreteProductA *>() );
  50. productFactory.RegisterObjectCreator("PRODUCT_B", boost::factory<ConcreteProductB *>() );
  51. //通过工厂生成对象, 存储在shared_ptr中.
  52. Product_ptr productA( productFactory.MakeObject("PRODUCT_A") );
  53. Product_ptr productB( productFactory.MakeObject("PRODUCT_B") );
  54. // 演示多态性质。
  55. productA->DoSomething();
  56. productB->DoSomething();
  57. return 0;

boost::factory<T*>()(arg1,arg2,arg3)  // same as new T(arg1,arg2,arg3)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/51372
推荐阅读
相关标签
  

闽ICP备14008679号