本文主要是介绍【重读设计模式】单体模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
说到设计模式,几乎所有人说的第一个模式就是单体模式,实在是因为单体模式太简单了。单体模式几乎和简单工厂模式一样简单,另外一方面这个模式的使用场景也是太多了,几乎所有的系统都会使用的设计模式。
定义:确保一个类只有一个实例,并提供一个全局访问点。
// Name : singleton.cpp
// Author : tester
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <pthread.h>
using namespace std;
class CDBAccess
{
public:
//获取实例,必须是静态函数
static CDBAccess* getInstance()
{
pthread_mutex_lock(p_mutex);
if(NULL == m_stance)
{
m_stance = new CDBAccess;
}
return m_stance;
}
int init()
{
//... 初始化数据库连接的代码
return 0;
}
int exec_query(char* sql, mysql_result** result)
{
//... 执行sql的代码
printf("exec sql succ.\n");
return 0;
}
private:
//构造函数必须声明为私有的
CDBAccess()
{};
private:
static CDBAccess* m_stance;
static pthread_mutex_t p_mutex;
};
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
int ret = CDBAccess::getInstance()->exec_query();
return 0;
}
这篇关于【重读设计模式】单体模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!