推荐文章:http://www.jellythink.com/archives/82
前言:
这两天各种各样的事,耽误了分享,今天按照之前定好的顺序分享3种设计模式出来。
类图:
类解读:
建立一个类,此类只可以有一个实例。
Singleton只有一个实例,。
实现原理:
类的内存分配是由构造函数实现的,因此只要控制类的构造函数即可保证类实例化的数量,实现如下代码,如下代码有四种实现方式,但在实例化的过程中会考虑到内存销毁及多线程调用,均在如下代码中得以实现。
实现代码:
1、最简单的单例代码:
class Singleton{public:static Singleton *GetInstance(){return const_cast <Singleton *>(m_Instance);}static void DestoryInstance(){if (m_Instance != NULL ){delete m_Instance;m_Instance = NULL ;}}int GetTest(){return m_Test;}private:Singleton(){ m_Test = 10; }static const Singleton *m_Instance;int m_Test;};const Singleton *Singleton ::m_Instance = new Singleton();int main(int argc , char *argv []){Singleton *singletonObj = Singleton ::GetInstance();cout<<singletonObj->GetTest()<<endl;Singleton ::DestoryInstance();}
2、多线程考虑:
为防止多线程导致创建多个实例,用如下方式:
#include <iostream>
using
namespace
std
;
class
Singleton
{
public
:
static
Singleton
*
GetInstance
(
)
{
if
(
m_Instance
==
NULL
)
{
Lock
(
)
;
// C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
if
(
m_Instance
==
NULL
)
{
m_Instance
=
new
Singleton
(
)
;
}
UnLock
(
)
;
// C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
}
return
m_Instance
;
}
static
void
DestoryInstance
(
)
{
if
(
m_Instance
!=
NULL
)
{
delete
m_Instance
;
m_Instance
=
NULL
;
}
}
int
GetTest
(
)
{
return
m_Test
;
}
private
:
Singleton
(
)
{
m_Test
=
0
;
}
static
Singleton
*
m_Instance
;
int
m_Test
;
}
;
Singleton
*
Singleton
::
m_Instance
=
NULL
;
int
main
(
int
argc
,
char
*
argv
[
]
)
{
Singleton
*
singletonObj
=
Singleton
::
GetInstance
(
)
;
cout
<<
singletonObj
->
GetTest
(
)
<<
endl
;
Singleton
::
DestoryInstance
(
)
;
return
0
;
}
3、内存自动销毁:
方法一:
#include <iostream>
using
namespace
std
;
class
Singleton
{
public
:
static
Singleton
*
GetInstance
(
)
{
static
Singleton
m_Instance
;
return
&m_Instance
;
}
int
GetTest
(
)
{
return
m_Test
++
;
}
private
:
Singleton
(
)
{
m_Test
=
10
;
}
;
int
m_Test
;
}
;
int
main
(
int
argc
,
char
*
argv
[
]
)
{
Singleton
*
singletonObj
=
Singleton
::
GetInstance
(
)
;
cout
<<
singletonObj
->
GetTest
(
)
<<
endl
;
singletonObj
=
Singleton
::
GetInstance
(
)
;
cout
<<
singletonObj
->
GetTest
(
)
<<
endl
;
}
方法二:
#include <iostream>
using
namespace
std
;
class
Singleton
{
public
:
static
Singleton
*
GetInstance
(
)
{
return
m_Instance
;
}
int
GetTest
(
)
{
return
m_Test
;
}
private
:
Singleton
(
)
{
m_Test
=
10
;
}
static
Singleton
*
m_Instance
;
int
m_Test
;
// This is important
class
GC
{
public
:
~
GC
(
)
{
// We can destory all the resouce here, eg:db connector, file handle and so on
if
(
m_Instance
!=
NULL
)
{
cout
<<
"Here is the test"
<<
endl
;
delete
m_Instance
;
m_Instance
=
NULL
;
}
}
}
;
static
GC
gc
;
}
;
Singleton
*
Singleton
::
m_Instance
=
new
Singleton
(
)
;
Singleton
::
GC
Singleton
::
gc
;
int
main
(
int
argc
,
char
*
argv
[
]
)
{
Singleton
*
singletonObj
=
Singleton
::
GetInstance
(
)
;
cout
<<
singletonObj
->
GetTest
(
)
<<
endl
;
return
0
;
}