<分区>
我有一个单例 A,我将在整个 B 类中使用它,因此在多个方法中使用 A::getInstance() 比尝试将引用 A& ref_ 存储到该单例中并没有多大意义只需调用 ref_ 的方法即可。问题是:当所有构造函数、复制构造函数、复制赋值运算符都是私有(private)的时,我如何获取和存储 A&ref_?我将如何解决这个问题?
--丹尼尔。
<分区>
我有一个单例 A,我将在整个 B 类中使用它,因此在多个方法中使用 A::getInstance() 比尝试将引用 A& ref_ 存储到该单例中并没有多大意义只需调用 ref_ 的方法即可。问题是:当所有构造函数、复制构造函数、复制赋值运算符都是私有(private)的时,我如何获取和存储 A&ref_?我将如何解决这个问题?
--丹尼尔。
最佳答案
The problem is: how do I get and store A& ref_, when all constructors, copy constructors, copy assignment operators are private?
考虑一下:
class A { // singleton
A(); // private
public:
static A& GetInstance() { // public singleton instance accessor
static A instance; // initialized on first call to GetInstance
return instance;
}
};
class B {
A& ref;
public:
B(): ref( A::GetInstance() ) {} // ref now points to the singleton instance
};
也就是说,请尽量不要在代码中使用单例。单例是一种增加模块相互依赖性的设计模式,使代码更加单一且更难测试。
更好的解决方案可能是这样的:
class A { // NOT a singleton
public:
A(); // public
};
class B {
A& ref;
public:
B(A& aref): ref( aref ) {} // ref now points to the injected instance
// but doesn't impose that A::GetInstance
// exists (aref is dependency-injected)
};
客户端代码:
A& a = [local object or anything else];
B b(a); // now you can inject any A instance and have no imposition
// in B's implementation that A must be a singleton.
关于c++ - 在 C++ 类中初始化单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23989129/