极速多用户网页音乐播放器(框架固定形式/底部音乐播放器)
<div><p>此网页使用了框架,但您的浏览器不支持框架。</p></div>

单例的实现方法

一种方法:

Singleton.h代码如下:

View Code
 1 #ifndef _SINGLETON_H_
 2 #define _SINGLETON_H_
 3 
 4 class Singleton
 5 {
 6 public:
 7     int getValue();
 8     static Singleton* Instance();
 9 private:
10     Singleton();
11     ~Singleton();
12 
13     int _iValue;
14     static Singleton* _Instance;
15 };
16 #endif

Singleton.cpp代码如下:

View Code
 1 #include "Singleton.h"
 2 #include <cstdlib>
 3 
 4 Singleton* Singleton::_Instance = NULL;
 5 
 6 Singleton::Singleton()
 7 {
 8     
 9 }
10 Singleton::~Singleton()
11 {
12     if (NULL != _Instance)
13     {
14         delete _Instance;
15         _Instance = NULL;
16     }
17 }
18 Singleton* Singleton::Instance()
19 {
20     if (NULL == _Instance)
21     {
22         _Instance = new Singleton;
23     }
24     return _Instance;
25 }
26 int Singleton::getValue()
27 {
28     return _iValue;
29 }

测试代码如下:

View Code
1 #include "Singleton.h"
2 #include <cstdlib>
3 
4 int main(int argc, char** argv)
5 {
6     int value = Singleton::Instance()->getValue();
7     return EXIT_SUCCESS;
8 }

另外的方法:

Singleton.h代码如下:

View Code
 1 #ifndef _SINGLETON_H_
 2 #define _SINGLETON_H_
 3 
 4 class Singleton
 5 {
 6 public:
 7     int getValue();
 8     static Singleton* Instance();
 9 private:
10     Singleton();
11     ~Singleton();
12 
13     int _iValue;
14 };
15 #endif

Singleton.cpp代码如下: 

View Code
 1 #include "Singleton.h"
 2 #include <cstdlib>
 3 
 4 Singleton* Singleton::_Instance = NULL;
 5 
 6 Singleton::Singleton()
 7 {
 8     
 9 }
10 Singleton::~Singleton()
11 {
12     
13 }
14 Singleton* Singleton::Instance()
15 {
16     static Singleton m_Singleton;
17     return &m_Singleton;
18 }
19 int Singleton::getValue()
20 {
21     return _iValue;
22 }

 

posted @ 2013-04-14 23:58  飞鼠溪  阅读(124)  评论(0编辑  收藏  举报