单例模式的两种实现模式
单例模式的两种实现方式
1. 饿汉模式:
#include <iostream> using namespace std; class Singleton { public: static Singleton& getInst (void) { return s_inst; } private: Singleton (void) {} Singleton (const Singleton&); static Singleton s_inst; }; Singleton Singleton::s_inst; int main (void) { Singleton& s1 = Singleton::getInst (); Singleton& s2 = Singleton::getInst (); Singleton& s3 = Singleton::getInst (); cout << &s1 << ' ' << &s2 << ' ' << &s3 << endl; return 0; }
2 . 懒汉模式
#include <iostream> using namespace std; class Singleton { public: static Singleton& getInst (void) { if (! m_inst) m_inst = new Singleton; ++m_cn; return *m_inst; } void releaseInst (void) { if (m_cn && --m_cn == 0) delete this; } private: Singleton (void) { cout << "构造:" << this << endl; } Singleton (const Singleton&); ~Singleton (void) { cout << "析构:" << this << endl; m_inst = NULL; } static Singleton* m_inst; static unsigned int m_cn; }; Singleton* Singleton::m_inst = NULL; unsigned int Singleton::m_cn = 0; int main (void) { Singleton& s1 = Singleton::getInst (); Singleton& s2 = Singleton::getInst (); Singleton& s3 = Singleton::getInst (); cout << &s1 << ' ' << &s2 << ' ' << &s3 << endl; s3.releaseInst (); s2.releaseInst (); s1.releaseInst (); return 0; }
两种模式的区别:懒汉模式中只有一个静态变量,调一次通过getInst函数返回一次,大家都用的这一个变量。懒汉模式里边维护了一个静态指针变量和一个静态变量做计数器,每次调的时候会先判断有没有构造,如果构造过m_inst就是非空的,计数器直接++就好,调用析构的话就是判断计数器,没人用的时候释放这块内存。
版权声明:本文为博主原创文章,未经博主允许不得转载。