[英]What are the drawbacks if the Singleton constructor is made protected - Inheritance - C++11?
我希望该类继承单例类。 因此,我需要使构造函数受保护而不是私有。 另外,我知道静态方法不能被覆盖,因为静态是类成员。 现在的问题是,如果我要使构造函数受到保护,会不会有问题? 单例场景中的受保护构造函数是否有缺点? 我在参考C ++。
我认为使构造函数受保护没有任何缺点。 受保护的访问说明符旨在用于继承。
如果不对基类构造函数进行保护,您将如何创建派生类对象?
下面是一个简单的实现。
class Base {
public:
static Base* getInstance() {
if(Base::_instance == NULL)
Base::_instance = new Base();
return Base::_instance;
}
protected:
Base() {}
private:
static Base* _instance;
};
在.cpp文件中:
Base::_instance = NULL;
class Derived : public Base {
public:
static Derived* getInstance() {
if(instance == NULL)
_instance = new Derived;
return _instance;
}
private:
static Derived* _instance;
};
简短答案:请勿。 您可能有充分的理由使用单例(不太可能,但是到底是怎么回事)。 我几乎不认为您有充分的理由让一个单例衍生自另一个单例。
这是完全没有用的。 创建Derived
实例时,将创建Base
实例。
只需使Derived
为单例,并使用公共构造函数将Base
作为标准类。
Singleton设计模式是指用于创建Class实例的接口。 这仅意味着您要实例化的具体类。 没有潜在的抽象基类。
我认为其他一些帖子曲解了OP的含义,所以我只给我2美分:)。 我认为OP正在讨论以下结构:
template<class A>
class Singleton // class that defines what is means to be Singleton
{
private:
protected:
Singleton() = default;
public:
static A& instance()
{
static A a;
return a;
}
};
class DerivedSingleton: public Singleton<DerivedSingleton> // Make concrete Singleton
{
friend Singleton<DerivedSingleton>;
private:
DerivedSingleton();
public:
void DerivedMethod();
};
// .. some code ...
DerivedSingleton::instance().DerivedMethod(); // call method
在这种情况下,将Singleton
构造函数设置为protected
不会出现任何问题。 掌握DerivedSingleton
的唯一方法是通过Singleton
类的instance
函数。 我对Singleton是否是一个好的设计模式没有意见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.