代码之家  ›  专栏  ›  技术社区  ›  Nick Meyer

C++中的工厂模式和类模板

  •  0
  • Nick Meyer  · 技术社区  · 15 年前

    在C++中如何实现与下面类似的法律设计?

    template<class T> class IProduct
    {
    public:
       virtual void doWork(const T & data) = 0;
    };
    
    template<class T> class ProductA : public IProduct<T> {/*...*/};
    template<class T> class ProductB : public IProduct<T> {/*...*/};
    
    class IProductFactory
    {
    public:
       template<class T> virtual IProduct<T> * createProduct() = 0;
    };
    
    class ProductAFactory: public IProductFactory
    {
    public:
       template<class T> virtual IProduct<T> * createProduct()
       {
          return new ProductA<T>;
       }
    };
    
    class ProductBFactory: public IProductFactory
    {
    public:
       template<class T> virtual IProduct<T> * createProduct()
       {
          return new ProductB<T>;
       }
    };
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   bshields    15 年前

    为什么你不能模板化 IProductFactory T 也?那会消除你的错误,而且它也同样普遍。客户还得知道 T型 是为了给 createProduct 方法。

    为此,您只需创建一个模板化函数来创建工厂。所以:

    template<class T> IProductFactory<T>* getProductFactory();
    

    现在你的工厂被模板化了 创建产品 方法不再是成员模板。不确定返回 ProductAFactory ProductBFactory 但您要么必须传入一个字符串来进行选择,要么让它成为另一个类的成员函数来做出决定,要么有多个自由函数,但只向特定客户机公开一个或另一个版本。

        2
  •  -2
  •   Jay    15 年前

    这不需要模板。这能解决你的问题吗?

    推荐文章