读书人

这个单实例模式有什么有关问题吗

发布时间: 2012-04-06 12:22:24 作者: rapoo

这个单实例模式有什么问题吗?
这样写有什么问题吗?目的就是做单实例模式
指针的创建和销毁都通过函数调用实现

// 头文件
public:
static CBMUService* CreateInstance();
static CBMUService* GetInstance();
static CBMUService* DestroyInstance();

// 源文件
CService* CService::m_pInstance = NULL;

CService* CService::CreateInstance()
{
if (NULL == m_pInstance)
{
m_pInstance = new CService;
if (NULL != m_pInstance)
{
return m_pInstance;
}
else
{
return NULL;
}
}
}

/***********************************************************************
* description: 获取实例指针
* remark:
************************************************************************/
CService* CService::GetInstance()
{
return m_pInstance;
}

/***********************************************************************
* description: 销毁实例
* remark:
************************************************************************/
CService* CService::DestroyInstance()
{
if (NULL != m_pInstance)
{
delete m_pInstance;
m_pInstance = NULL;
}
}

[解决办法]
单线程没问题,多线程中Double Check也不一定行,
具体请Google陈硕的《当析构遇到多线程》文章
[解决办法]
这个应该是单线程的单例 没有用到锁的

DestroyInstance是为了释放的 其实没多大必要,可以用auto_ptr代替
[解决办法]
ps:

C/C++ code
        if (NULL != m_pInstance)         {             return m_pInstance;         }         else         {             return NULL;         }
[解决办法]
你这个还要考虑singleton 的子类也单件吧。
一种方法是在父类中根据1个变量来选择要单件的singleton子类。
一种方法是在子类中实现instance方法,这种不够灵活。
下面是第一种方法。第二种就不举例了。
C/C++ code
CService* CService::Instance() {     if (NULL == m_pInstance)     {         const char* servicename=getenv("serviceName");        if(strcmp(servicename,"service1")==0)          m_pInstance = new CService1;         else if(strcmp(servicename,"service2")==0)          m_pInstance = new CService2;        //...  下省略         else          m_pInstance = new CServicen;     }              return m_pInstance; }
[解决办法]
C/C++ code
CService* CService::CreateInstance() {     if (NULL == m_pInstance)     {         m_pInstance = new CService;         // 既然m_pInstance非NULL return m_pInstance;         // m_pInstance NULL 也是return m_pInstance; (NULL)        // 那下面这个if...else...语句直接用 return m_pInstance;就行了        if (NULL != m_pInstance)         {             return m_pInstance;         }         else         {             return NULL;         }     }       // 其实这里应该return m_pInstance的,因为如果 NULL != m_pInstance该怎么办呢       }
[解决办法]
探讨
DestroyInstance如果不用,就是在需要释放的地方写delete了~大家觉得对吧?

[解决办法]
呃,讨论单件的销毁问题,请先找本《modern c++ design》看看,免得闭门造车。
另外,没加锁的单件,还不如全局变量了。
[解决办法]
如果你销毁了 然后又有线程不晓得 又调用了你的单件怎么办

参考《设计新思维》 有章对单件的单独探讨。 有个phoenix singleton

读书人网 >C++

热点推荐