Windows CE 3.0Windows CE 2.11Pocket PC 2002Windows MobileVisual Studio 6Visual C++ 7.0.NET 1.0Windows 2000Visual C++ 6.0Windows XP移动应用中级开发Visual StudioWindowsC++.NET
微型 Singleton 助手类






4.17/5 (6投票s)
2002年8月8日

97160

522
SingleT 将为您提供一种便捷的方式来实现单例模式。
引言
有时我们需要编写使用“单例”的代码。如果您不知道什么是单例,可以在许多设计模式书籍中阅读相关内容。单例原则非常简单。
如您所知,如果您对单例对象使用引用指针,那么在程序终止时必须删除它。但这很好,因为它实现了“延迟实例化”。
我希望自动终止单例对象,并延迟实例化。因此,我编写了这个类。
优点
- 延迟实例化。
- 安全自动终止。
- 对象和单例代码分离。
这是我的微型单例助手类 - CSingletonT<>
,我希望它能帮助您。
// // Using singletonT class // #include "SingletonT.h" // test class class CObj { protected: CObj(){ x = 0 ; TRACE("Created CObj\r\n"); } public: virtual ~CObj(){ x = 0 ; TRACE("Deleted CObj\r\n");} int x; }; // Testing void CTestSingleTDlg::OnButton1() { // TODO: Add your control notification handler code here // if first call, then singleton object will instance ( instance lately ) CObj* o = CSingletonT<CObj>::GetObject(); // use singletone object o->x ++; TRACE("o->x = %d\r\n",o->x); }
如果它有效,您将看到类似于示例图片中的输出
希望对您有所帮助,谢谢!