我有一个 System 类,它可以返回一个指向 Editor 类的指针。 Editor 类在 System 类中实例化,并将指针传递给 System 的私有(private)变量。 Editor 类本质上充当System 内部数据结构的替代接口(interface)。
我的问题: 是否存在允许我禁止直接实例化 Editor 类但仍以某种方式在 System 中实例化它的设计模式?
谢谢。
最佳答案
您可以将 Editor 的构造函数设为私有(private),这样可以防止其他人实例化它,然后将 System 设为好友将允许它访问构造函数。
class System {
public:
System() : editor_(new Editor()) { ... }
private:
Editor* editor_;
}
class Editor {
friend class System;
Editor() { ... }
}
关于C++模式禁止在特定范围外实例化类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3589064/