本文共 1533 字,大约阅读时间需要 5 分钟。
单例模式非常经典,很有用处,在某些特定用途特别有用。
例如,日志模块,我们希望只存在一个实例,就可以用单例模式。
下面是单例模式的经典代码,把下面 C++ 代码片段中的 Singleton 替换成实际类名, 快速得到一个单例类:
1.引用版本
#includeusing namespace std;class Singleton {public: static Singleton& Instance() { static Singleton theSingleton; return theSingleton; } /* more (non-static) functions here */ void dosome() { cout << "this is true" << endl; }private: Singleton(){} // ctor hidden Singleton(Singleton const&); // copy ctor hidden Singleton& operator=(Singleton const&); // assign op. hidden ~Singleton(){} // dtor hidden};int main (){ Singleton &s=Singleton::Instance(); s.dosome(); return 0;}//----
2.指针版本
#includeusing namespace std;class Singleton {public: static Singleton* Instance() { static Singleton theSingleton; return &theSingleton; } /* more (non-static) functions here */ void dosome() { cout << "this is true" << endl; }private: Singleton(){} // ctor hidden Singleton(Singleton const&); // copy ctor hidden Singleton& operator=(Singleton const&); // assign op. hidden ~Singleton(){} // dtor hidden};int main (){ Singleton *sc; sc = Singleton::Instance(); sc->dosome(); Singleton *sc2; sc2 = Singleton::Instance(); sc2->dosome(); if (sc == sc2) { cout << "The same" << endl; } return 0;}//--
这是经典例子,记好,好用。
------------------