C++抽象类的工厂方法模式
我必须在 C++ 中实现工厂方法模式。由工厂“组装”的类 (C) 是抽象的,并且由其他某个类 (D) 继承。所以我不希望C有构造函数。但要创建 D 的实例,C 必须至少有一个受保护的构造函数。但随后有人可能会从 C 派生并以这种方式创建 C 的实例。我不希望这种事发生。所以我创建了一个受保护的构造函数,它接受一个指向 C 对象的指针以供派生类使用,代码如下。问题是这是否是处理这个问题的正确方法。
class C {
private:
C() {}
protected:
C(const C* c) {}
friend class CFactory
};
class D: public C
{
private:
D(const C* c): C(c) {}
friend class CFactory;
};
class CFactory
{
public:
static C* createC() {
C* ptr = new C();
ptr = new D(ptr); // There is garbage collection on the project, so no memory leak.
}
};
I have to implement a factory method pattern in C++. The class (C) that is to be "assembled" by the factory is abstract and is inherited by some other class (D). So I don't want C to have a constructor. But to create an instance of D, C has to have at least a protected constructor. But then someone might derive from C and create an instance of C in this way. I don't want this to happen. So I created a protected constructor that takes a pointer to a C object for derived classes to use, code is below. The question is whether that is the correct way of dealing with this issue.
class C {
private:
C() {}
protected:
C(const C* c) {}
friend class CFactory
};
class D: public C
{
private:
D(const C* c): C(c) {}
friend class CFactory;
};
class CFactory
{
public:
static C* createC() {
C* ptr = new C();
ptr = new D(ptr); // There is garbage collection on the project, so no memory leak.
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为 C 提供一个私有构造函数并使 D 成为 C 的友元类可能是更好的选择。
It's probably a better option to give C a private constructor and make D a friend class of C.
您在工厂中创建 C 对象进行复制有什么原因吗?
如果不是:
你让 D 成为 C 的朋友,为 D 创建一个默认构造函数,并且在工厂中只有:
它会简化事情。
Is there a reason you are making a C object to copy in the factory?
If instead of:
you made D a friend to C, made a default constructor for D, and in the factory only had:
It would simplify things.