这是一种合法的创建基础单例对象的方式吗?它可以确保所有子对象也都是单例。我想将它与工厂模式结合使用,以确保所有工厂都是单例。
关键类旨在防止子类绕过单例构造函数,但实际上只是一个形式参数。
特别是这种方法是否存在任何问题?
class singleton
{
protected:
struct key
{
private:
friend class singleton;
key(){}
};
public:
singleton(const key&)
{}
template <class child> static child* getInstance()
{
static key instanceKey;
static child* unique = new child(instanceKey);
return unique;
}
private:
};
class test : public singleton
{
public:
test(singleton::key& key)
: singleton(key)
{}
void init()
{
//init object
}
private:
};
int main()
{
test* t = singleton::getInstance<test>();
return 0;
}