单件类的实现
/******************************************** * CopyRight 2007 北京交通大学 * 程序名称: 单件类 * 文件名: main.cpp * 修改日期: 2007-4-7 19:56:09 * 描述: 设计模式中的单件类的简单实现 * ********************************************/ #include <iostream> #include "conio.h" using namespace std; class Singleton { public: static Singleton *Getinstance() { if (p != NULL) { cout << "已经创建过了单件类,无法二次创建!" << endl; return p; } else { cout << "系统未创建过单件类,为单件类分配内存" << endl; p = new Singleton; return p; } } static Singleton *Free() { if (p != NULL) { delete p; p = NULL; return NULL; } else return NULL; cout << "释放单件类.." << endl; } static ShowInstance() { cout << "类内返回的单件类地址:" << p << endl; } private: static Singleton *p; Singleton(){}; ~Singleton(){}; }; Singleton *Singleton::p = NULL; int main() { cout << "\n单件类测试 \n\n"; class Singleton *p = NULL; cout << "创建前:\n程序获取单件类地址:" << p << endl; Singleton::ShowInstance(); cout << "\n创建:" << endl; p = Singleton::Getinstance(); Singleton::ShowInstance(); cout << "程序获取的单件类地址:" << p << endl; cout << "\n二次创建试验:\n"; Singleton::Getinstance(); p = Singleton::Free(); cout << "\n释放后:\n单件类地址" << p << endl; Singleton::ShowInstance(); cout << "\n按任意键退出."; getch(); return 0; }