c++ - 与 get_instance() 分离的单例构造函数

标签 c++ design-patterns constructor singleton

在典型的单例中,构造函数在第一次调用 getInstance() 时被调用。我需要的是将 init 和 getInstance 函数分开。 init 函数必须创建实例 using constructor 并且 getInstance 只能在 init 函数被调用时使用(否则它会抛出异常)。我该怎么做?

    Singleton::init(required argument); //calls constructor
    Singleton::getInstance(); //only possible if init had been called, otherwise throws exception

最佳答案

在 init 方法中设置一个 bool 值,表示 init 成功。在 getInstance 方法中,如果为假则抛出异常。

您可以将其作为静态私有(private)成员存储在类中。

#include <iostream>
class Single
{
public:
    static void init(int x)
    {
        single.number = x;
        inited = true;
    }

    static Single & GetInstance()
    {
        //Do exception stuff here....
        if(inited)
        {
            std::cout << "Inited" << std::endl;
        }
        else
        {
            std::cout << "NOT Inited" << std::endl;
        }
        return single;
    }


    void printTest()
    {
    std::cout << single.number << std::endl;
    }

private:
    Single() : number(5)
    {
        std::cout << "Construction " << std::endl;
    }

    int number;
    static bool inited;
    static Single single;
};

bool Single::inited = false;
Single Single::single;

int main()
{
    std::cout << "Entering main" << std::endl;

    Single::GetInstance();
    Single::init(1);
    Single::GetInstance().printTest();

}

程序输出:

Construction 
Entering main
NOT Inited
Inited
1

关于c++ - 与 get_instance() 分离的单例构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14792286/

相关文章:

java - 游戏中!框架 我可以在模型包 Singleton 中创建类吗?

c++ - 在临时对象上复制构造函数 c++

javascript - 从js引擎的 Angular 看闭包和构造函数是如何工作的

c++ - c 中的错误,但不是 c++ 中的错误

javascript - 最佳实践导致臃肿的容器和非模块化代码

c++ - 带有 Armadillo 可选参数的函数

javascript - 将异步调用转换为同步?

javascript - typescript 定义构造函数或函数?

c++ - 遍历并非所有元素都应具有值的元素

c++ - c++中的 boolean 乘法?