【问题标题】:Singleton constructor separated from get_instance()与 get_instance() 分离的单例构造函数
【发布时间】:2013-02-09 22:24:32
【问题描述】:

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

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

【问题讨论】:

  • 不要使用单例并解决问题。
  • 你有什么问题?
  • 呃-哦。您真正要解决的根本问题是什么。单例模式可能不是您的答案。
  • 好吧,经过一番思考,我认为我可能不会使用单例。

标签: c++ design-patterns constructor singleton


【解决方案1】:

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

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

#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

【讨论】:

  • 是的,但我仍然不知道应该在哪里存储它的静态实例。我需要调用构造函数,这是我的问题。如果 init 函数是普通的成员函数,这将起作用。
  • 谢谢,但我仍然如何将构造函数放入 init 方法?我认为这样我仍然无法使用 init() 调用实例构造函数。
  • @user1873947 我认为误解是静态的工作原理。单例对象的构造发生在调用 main 之前。我更新了代码以包含可以帮助您理解排序的打印语句。出于所有意图和目的,您的 init 方法是您的构造函数。正如其他人在 cmets 中所说,如果您可以避免单例,那是最好的。它们会导致可扩展性问题。
猜你喜欢
  • 2011-04-19
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多