#include "stdafx.h" #include <iostream> template<typename T> class Singleton { public: static T& Instance() { static T theSingleInstance; return theSingleInstance; } }; class OnlyOne : public Singleton<onlyone> { public: OnlyOne() { test = 10; } //OnlyOne(int _test) { test = _test; } void SetTest(int _test) { test = _test; } int GetTest() { return test; } private: OnlyOne& operator= (const OnlyOne& lhs) {} OnlyOne(OnlyOne& rhs) {} friend class Singleton<onlyone>; int test; }; int _tmain(int argc, _TCHAR* argv[]) { OnlyOne* OTL = new OnlyOne; std::cout << OTL->Instance().GetTest() << std::endl; OnlyOne* XD = new OnlyOne; XD->SetTest(100); // 嘗試去更改test的值 std::cout << XD->Instance().GetTest() << std::endl; system("pause"); return 0; }該範例未考慮到多執行緒的考量,沒去檢查是否已存在,對於程式的overhead挺大的,也不安全,當初GoF有解決的方式,但經證實是錯誤的,也有許多人提出相對應的解決方法,有興趣的去此部落格參考。
4 年前
0 意見:
張貼留言