本文介绍一种很简单的可以自动回收资源的单例模式,平时也经常看别个写的技术文章,CSDN里面有很多牛人,他们写的文章通俗易懂,言简意赅,能给看文章的人带来美的享受。但也有很多写技术文章的童鞋文章冗长,屁话一大篇,浪费时间。好了我废话少说,希望本文对有需要的人能有所帮助:
- 测试环境:Linux CentOS7.2
直接上代码,小伙伴们可以复制到自己的环境里面编译运行。C++这东西,还是自己咀嚼才有味道。
代码块[SingletonLogManager.h]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: SingletonLogManager.h
* Author: Jerry
*
* Created on 2017年8月8日, 下午2:25
*/
#ifndef SINGLETONLOGMANAGER_H
#define SINGLETONLOGMANAGER_H
#include <iostream>
using namespace std;
class SingletonLogManager
{
public:
static SingletonLogManager* GetInstance(); // 获取一个实例
public:
void print();
protected:
SingletonLogManager();
~SingletonLogManager();
// 资源回收
class SingletonRecovery
{
public:
SingletonRecovery()
{
}
~SingletonRecovery()
{
cout << " begin to run destruction !" << endl;
if (m_pInstance != NULL)
{
delete m_pInstance;
m_pInstance = NULL;
}
}
};
// 资源回收类
static SingletonRecovery m_SR;
private:
static SingletonLogManager* m_pInstance; // 静态指针
};
#endif /* LOGTOOL_H */
代码块[SingletonLogManager.cpp]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: LogTool.cpp
* Author: Jerry
*
* Created on 2017年8月8日, 下午2:25
*/
#include <stdio.h>
#include <stdlib.h>
#include "SingletonLogManager.h"
// new一个实例
SingletonLogManager* SingletonLogManager::m_pInstance = new SingletonLogManager;
SingletonLogManager::SingletonRecovery SingletonLogManager::m_SR;
SingletonLogManager::SingletonLogManager()
{
}
SingletonLogManager::~SingletonLogManager()
{
}
// 获取实例
SingletonLogManager* SingletonLogManager::GetInstance()
{
return m_pInstance;
}
void SingletonLogManager::print()
{
printf("SingletonLogManager::print()\n\n");
}
代码块[main.cpp]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: LogTool.cpp
* Author: Jerry
*
* Created on 2017年8月8日, 下午2:25
*/
#include <iostream>
#include "SingletonLogManager.h"
void testRecovery()
{
SingletonLogManager* pSingletonLogManager = SingletonLogManager::GetInstance();
pSingletonLogManager->print();
}
int main()
{
cout << "testRecovery begin !" << endl;
testRecovery();
cout << "testRecovery end !" << endl;
return 0;
}