可可西

单件模式

单件模式要保证的是:类只能实例化一个对象。

为了保证这点,需要将类的构造函数析构函数声明为私有类型

代码如下:

 1 class single
 2 {
 3 private:
 4     single():m_chs("Hello"){}
 5     ~single(){}
 6 
 7 public:
 8     void printHello()
 9     {
10         printf("%s\n",m_chs);
11     }
12 
13 public:
14     static single* getInstance()
15     {
16         if (!m_instance) m_instance=new single;
17         return m_instance;
18     }
19     static void release()
20     {
21         if (m_instance) delete m_instance;
22     }
23 
24 private:
25     static single* m_instance;
26     const char* m_chs;
27 };
28 
29 single* single::m_instance = NULL;
30 
31 
32 int main(int argc, char* argv[])
33 {
34     single* a = single::getInstance();
35     a->printHello();
36     single::release();
37     return 0;
38 }

posted on 2012-04-13 13:49  可可西  阅读(245)  评论(0编辑  收藏  举报

导航