您的位置:首页 > 编程语言 > C语言/C++

C++设计模式--单例、策略模式

2015-09-08 18:25 323 查看
单例模式:保证某个类在全局模块只有一个访问点,即只存在一个实例,被全局共享。

.h:

class CSingleton
{
public:
static CSingleton* Initlize();
static void Uninilize();
static CSingleton* GetInstance();
private:
CSingleton();
~CSingleton();
private:
static CSingleton* m_pInstance;
};




.cpp

CSingleton* CSingleton::m_pInstance = NULL;

CSingleton::CSingleton()
{
}

CSingleton::~CSingleton()
{
}

CSingleton* CSingleton::Initlize()
{
return GetInstance();
}

void CSingleton::Uninilize()
{
if (m_pInstance != NULL)
{
delete m_pInstance;
m_pInstance = NULL;
}
}

CSingleton* CSingleton::GetInstance()
{
if (m_pInstance == NULL)
{
m_pInstance = new CSingleton;
}
return m_pInstance;
}


策略模式:

策略模式:封装不同的算法,不同的算法可以相互替换,而外部调用则不用过多修改。他们是为了实现同样的目的,只是实现不同,对外接口都是一样的。

在基本的使用中,选择所用具体实现的职责是由客户端来调用,并交给策略模式的对象。

主要是面向对象的继承和多态的应用,常与工厂模式联合使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单例 策略 设计模式