代码设计模式之单例模式(Singleton)

来源:互联网 发布:fifaonline308年数据库 编辑:程序博客网 时间:2024/06/07 14:30

单例模式

在开发中用得比较多的一种模式,如果读写配置,日志等。在一个应用程序整个生命周期中有且只有一个实例产生。

而这个实例由自身的类方法(静态方法)来创建。

 

systemconfig.h

#ifndef SYSTEMCONFIG_H#define SYSTEMCONFIG_Hclass SystemConfig{public:SystemConfig(void);~SystemConfig(void);static SystemConfig* getInstance();void readconfig();void writeconfig();private:static SystemConfig* m_sconfig;};#endif

systemconfig.cpp

#include "StdAfx.h"#include "systemconfig.h"#include "iostream"SystemConfig* SystemConfig::m_sconfig = NULL;SystemConfig::SystemConfig(void){}SystemConfig::~SystemConfig(void){}SystemConfig* SystemConfig::getInstance(){if (!m_sconfig){m_sconfig = new SystemConfig();}return m_sconfig;}void SystemConfig::readconfig(){std::cout<<"read a config from config file"<<std::endl;}void SystemConfig::writeconfig(){std::cout<<"write a config to config file"<<std::endl;}

 

测试调用单例

#include "stdafx.h"#include "stdlib.h"#include "systemconfig.h"int _tmain(int argc, _TCHAR* argv[]){SystemConfig *cfg = SystemConfig::getInstance();cfg->readconfig();cfg->writeconfig();system("pause");return 0;}




 

原创粉丝点击