#include "stdafx.h"
#include <iostream>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <boost/assert.hpp>
using namespace boost;
// class SingletonObject
// {
// public:
// static shared_ptr<SingletonObject> getInstene()
// {
// if (NULL == __m_ptrSingletonObject)
// {
// __m_ptrSingletonObject = make_shared<SingletonObject>();
// return __m_ptrSingletonObject;
// }
// return __m_ptrSingletonObject;
// }
//public:
// //对于构造函数是私有的不能用智能指针
// SingletonObject(){}
// virtual ~SingletonObject(){}
//public:
// static shared_ptr<SingletonObject> __m_ptrSingletonObject;
//};
class SingletonObject
{
public:
static SingletonObject* getInstence()
{
if (NULL == __m_ptrSingletonObject)
{
SingletonObject::__m_ptrSingletonObject = new SingletonObject();
return __m_ptrSingletonObject;
}
return __m_ptrSingletonObject;
}
private:
static SingletonObject* __m_ptrSingletonObject;
protected:
SingletonObject(){}
virtual ~SingletonObject(){}
CC_SYNTHESIZE(std::string,m_strData,Data);
};
SingletonObject* SingletonObject::__m_ptrSingletonObject = NULL;
void testSingletonMode()
{
SingletonObject *ptrInstance = SingletonObject::getInstence();
ptrInstance->setData("aaaaaaa");
std::cout << ptrInstance->getData() << std::endl;
SingletonObject *ptrInstance2 = SingletonObject::getInstence();
std::cout << ptrInstance2->getData() << std::endl;
BOOST_ASSERT(ptrInstance == ptrInstance2);
}
Singleton 单例模式
最新推荐文章于 2017-12-25 18:00:55 发布