设计模式 - C++中单例模式构造对象时需要传参数应该怎么做?
巴扎黑
巴扎黑 2017-04-17 13:14:19
0
2
551

《Effective C++》条款4中说要确定对象被使用之前已被初始化。
我现在win32程序有一个对象,将它设计为单例,但是它构造时需要传入hinstance和title参数进行构建。
我的做法是:

//winmain.cpp
RPhoton* RPEngine = RPhotonEngine::RPEngine(hInstance, L"RPhoton");
//RPhotonEngine.h
class RPhotonEngine
{
public:
    static RPhoton*            RPEngine(HINSTANCE hinstance, std::wstring title);
    static RPhoton*            RPEngine();

protected:
    RPhotonEngine();

private:
    static RPhoton*            g_RPhoton;
};
//RPhotonEngine.cpp
RPhoton* RPhotonEngine::g_RPhoton = nullptr;

RPhoton* RPhotonEngine::RPEngine(HINSTANCE hinstance, std::wstring title)
{
    if (g_RPhoton == nullptr)
    {
        g_RPhoton = new RPhoton(hinstance, title);
    }
    return g_RPhoton;
}

RPhoton* RPhotonEngine::RPEngine()
{
    return g_RPhoton;
}

RPhotonEngine::RPhotonEngine()
{
}

感觉这样做怪怪的,怎么改比较好??

巴扎黑
巴扎黑

reply all(2)
迷茫
class SomeEngine{
public:
    RPhoton* getInstance(HINSTANCE hinstance, std::wstring title){
        //check if hinstance or title is legal
        //then return the static instance
        static RPhoton* somePhoton = new RPhoton(hinstance, title);
        return somePhoton; 
    }
protected:
    SomeEngine(){}
};

C++ guarantees that the static variable in getInstance will only be initialized once.

伊谢尔伦

If you want to use a singleton and pass parameters, you can only add an Init function to pass parameters. The singleton still gets the instance of the object, but it is actually initialized during Init.

Reference class两阶段构造
https://msdn.microsoft.com/library/7ffyb1kb%28v=vs.110%29.aspx

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template