使用C ++中的私有构造函数的工厂模式

时间:2015-09-02 10:57:34

标签: c++ design-patterns factory-pattern

我正在尝试实现一个由

组成的工厂模式
  • 工厂类
  • 带有受保护构造函数的抽象类
  • 使用私有构造函数和虚拟公共继承的类 析构函数。

我想确保

  • 工厂以外的其他任何人都无法创建任何实例
  • 如果定义了新的继承类,则不需要对接口类和已定义的继承类进行任何修改。 Juts新类实现并添加到工厂类中创建方法。

我也不想为每个继承的类编写类似相同的代码(如每个inited的静态工厂方法),并让未来的开发人员为工厂连接留下更多工作。

,即使用pseduo代码

Intent mIntent = new Intent(context , SainarService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

以上代码是我提出的内容。任何建议(C ++的特色,不同的设计......)都是受欢迎的。

3 个答案:

答案 0 :(得分:3)

我认为这不是一个好主意,但这是一种方法。您创建一个只能由Factory创建的Tag类型,并使所有构造函数都采用该类型的参数。

class Factory;

class Tag
{
    Tag() {}
    friend Factory;
};

class Interface 
{
public:
    Interface(Tag t) {}
    virtual ~Interface() {}
};

struct Impl1: public Interface
{
    Impl1(Tag t): Interface(t) {}
};

class Factory
{
public:
   Interface* makeInstance()
   {
       return new Impl1( Tag{} );
   }
};

void foo()
{
    Impl1 i( Tag{} );
}

foo()您将收到编译错误,因为Tag::Tag是私有的。

答案 1 :(得分:0)

你可以有一个模板化的功能:

template<typename Type>
std::unique_ptr<Interface> make_interface() {
    // exceptions etc..
}

template<>
std::unique_ptr<Interface> make_interface<InheritedA>() {
    return std::make_unique<InheritedA>();
}

template<>
std::unique_ptr<Interface> make_interface<InheritedB>() {
    return std::make_unique<InheritedB>();
}

但我真的没有看到所有这些Javaesque样板中的重点。更不用说你正在无缘无故地将编译时信息(类型)转换为运行时信息(通过异常)。

我会选择:

std::unique_ptr<Interface> ptr_a = std::make_unique<InheritedA>();
std::unique_ptr<Interface> ptr_b = std::make_unique<InheritedB>();

需要时。

答案 2 :(得分:-3)

使用Factory很少是一种好习惯。我将它视为与辛格尔顿一起的反模式。在良好的设计中,classess并不关心它们是如何被创造出来的。在您的情况下,在Factory中使用时,如何使用自定义分配器创建类?堆栈?在共享内存中?在内存映射文件中?从缓冲区?到位?这在工厂里真的很难实现,但不要绝望 - 简单而优雅的解决方案就是放弃了工厂!