C ++工厂模式与模板

时间:2015-04-24 15:29:53

标签: c++ templates factory factory-pattern

我正在尝试使用c ++模板对抽象工厂进行编码。由于我在遇到麻烦之前从未做过这样的事情。我写的代码,你可以自己验证,是错误的,我不知道如何纠正它。我的想法是有两个模板化的类将包含base_class和derived_class,因此这个类可以用于任何类型的类。出于同样的原因,它也被模板化了。

#ifndef _t_factory_h_
#define _t_factory_h_

#include <iostream>
#include <map>

template < class T >
class base_creator
{
  public:
   virtual ~base_creator(){ };
   virtual T* create() = 0;
};


template < class derived_type , class base_type >
class derived_creator : public base_creator<base_type>
{
  public:
  base_type* create()
  {
   return new derived_type;
  }
};

template <class _key, class base >
class factory
{
   public:
     void register_type(_key id , derived_creator<derived_type,base_type>* _fn)
  {
    _function_map[id] = _fn;
  }

  base* create(_key id)
  {
    return _function_map[id]->create();
  }

 ~factory()
 {
   auto it = _function_map.begin();
   for(it ; it != _function_map.end() ; ++it)
   {
     delete (*it).second;
   }
  }

  private:
     std::map<_key , derived_creator<derived_type,base_type>*> _function_map;
   };

#endif /* defined _t_factory_h_ */

如果有人可以帮我纠正这段代码,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

问题解决了。 这是代码:

#ifndef _t_factory_h_
#define _t_factory_h_

#include <iostream>
#include <map>

template < class T >
class base_creator
{ 
  public:
  virtual ~base_creator(){ };
  virtual T* create() = 0;
};


template < class derived_type , class base_type >
class derived_creator : public base_creator<base_type>  
{
 public:
 base_type* create()
 {
  return new derived_type;
 }
};

template <class _key, class base_type >
class factory
{
 public:
   void register_type(_key id , base_creator<base_type>* _fn)
   {
     _function_map[id] = _fn;
   }

   base_type* create(_key id)
   {
      return _function_map[id]->create();
   }

  ~factory()
  {
    auto it = _function_map.begin();
    for(it ; it != _function_map.end() ; ++it)
    {
      delete (*it).second;
    }
}

 private:
   std::map<_key , base_creator<base_type>*> _function_map;
};

#endif /* defined _t_factory_h_ */