带模板的 C++ 工厂模式

问题描述 投票:0回答:2

我正在尝试使用 C++ 模板编写抽象工厂。因为在遇到麻烦之前我从来没有做过这样的事情。我写的代码,你可以自己验证,是错误的,我不知道如何纠正它。我的想法是,有两个模板类将包含 base_class 和导出_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_ */

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

c++ templates factory factory-pattern
2个回答
2
投票

问题解决了。 这是代码:

#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_ */

0
投票

在这里您可以找到基于模板的简单工厂的示例实现:https://nwrkbiz.gitlab.io/cpp-design-patterns/

© www.soinside.com 2019 - 2024. All rights reserved.