定义:
单件模式确保一个类只有一个实例,并提供一个全局访问点。
由于该模式的结构很简单,所以此处不再给出UML图,需要注意的是在下面实现代码中给出的一个多线程控制的类可以在其他代码中借鉴。关于该模式的实现还可以参考下面两个链接的实现,里面给出了更加完美的实现。
1. http://www.kuqin.com/design-patterns/20071113/2300.html
2. http://www.host01.com/article/software/cc/20060917184438144.htm
代码实现:
注意:在代码实现时注意考虑多线程安全的情况,另外还需要考虑内存的释放,这里只实现了多线程安全,内存的释放可以使用“智能指针”来实现,可以参考上面两个链接的实现
/************************************************************************/ /* Singleton.h */ /************************************************************************/ /** * @file Singleton.h * @brief Singleton模式的实现代码 * @author wlq_729@163.com * http://blog.youkuaiyun.com/rabbit729 * @version 1.0 * @date 2009-02-17 */ #ifndef SINGLETON_H_ #define SINGLETON_H_ #include <iostream> #include <windows.h> using namespace std; #define CLASS_UNCOPYABLE(classname) / private: / classname##(const classname##&); / classname##& operator=(const classname##&); class Mutex { CLASS_UNCOPYABLE(Mutex) public: Mutex() :_cs() { InitializeCriticalSection(&_cs); } ~Mutex() { DeleteCriticalSection(&_cs); } void lock() { EnterCriticalSection(&_cs); } void unlock() { LeaveCriticalSection(&_cs); } private: CRITICAL_SECTION _cs; }; class Lock { CLASS_UNCOPYABLE(Lock) public: explicit Lock(Mutex& cs) :_cs(cs) { _cs.lock(); } ~Lock() { _cs.unlock(); } private: Mutex& _cs; }; class ChocolateBoiler { private: ChocolateBoiler(); public: static ChocolateBoiler* getInstance(); void fill(); void drain(); void boil(); bool isEmpty(); bool isBoiled(); private: static ChocolateBoiler* uniqueInstance; private: static Mutex _mutex; bool empty; bool boiled; }; #endif /************************************************************************/ /* Singleton.cpp */ /************************************************************************/ #include "Singleton.h" Mutex ChocolateBoiler::_mutex; ChocolateBoiler* ChocolateBoiler::uniqueInstance = NULL; ChocolateBoiler* ChocolateBoiler::getInstance() { if (uniqueInstance == NULL) { Lock lock(_mutex); if (uniqueInstance == NULL) { uniqueInstance = new ChocolateBoiler(); } } return uniqueInstance; } ChocolateBoiler::ChocolateBoiler() { empty = true; boiled = false; } void ChocolateBoiler::fill() { if (isEmpty()) { empty = false; boiled = false; cout<<"在锅炉内填满巧克力和牛奶的混合物"<<endl; } } void ChocolateBoiler::drain() { if (!isEmpty() && isBoiled()) { empty = true; cout<<"排出巧克力和牛奶"<<endl; } } void ChocolateBoiler::boil() { if (!isEmpty() && !isBoiled()) { boiled = true; cout<<"将炉内物煮沸"<<endl; } } bool ChocolateBoiler::isEmpty() { return empty; } bool ChocolateBoiler::isBoiled() { return boiled; } /************************************************************************/ /* test.cpp */ /************************************************************************/ #include "Singleton.h" void main(void) { ChocolateBoiler* chocolateBoiler = ChocolateBoiler::getInstance(); chocolateBoiler->fill(); chocolateBoiler->boil(); chocolateBoiler->drain(); }
程序输出:
在锅炉内填满巧克力和牛奶的混合物
将炉内物煮沸
排出巧克力和牛奶
请按任意键继续. . .