设计模式 - C++中单例模式构造对象时需要传参数应该怎么做?

浏览:32日期:2023-05-24

问题描述

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

//winmain.cppRPhoton* RPEngine = RPhotonEngine::RPEngine(hInstance, L'RPhoton');

//RPhotonEngine.hclass RPhotonEngine{public: static RPhoton* RPEngine(HINSTANCE hinstance, std::wstring title); static RPhoton* RPEngine();protected: RPhotonEngine();private: static RPhoton* g_RPhoton;};

//RPhotonEngine.cppRPhoton* 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(){}

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

问题解答

回答1:

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

C++保证getInstance里的static变量只会被初始化一次。

回答2:

又要用单例, 又要传参, 那你只能增加一个Init函数, 用来做传参的动作了. 单例还是获取对象的实例, 只是Init的时候才真正的初始化.

参考类的两阶段构造https://msdn.microsoft.com/library/7ffyb1kb%28v=vs.110%29.aspx

相关文章: