DownloadManager.h
*/
#ifndef DOWNLOADMANAGER_H
#define DOWNLOADMANAGER_H
#include <string>
#include <pthread.h>
#include <stdlib.h>
#include <iostream>
#include <stdexcept>
using namespace std;
class DownloadManager{
private:
static pthread_mutex_t mutex;
string mName;
static DownloadManager *sInstance;
static bool destroyed;
DownloadManager(string name);//私有化。
const DownloadManager& operator=(const DownloadManager& src);//私有化。
DownloadManager(const DownloadManager&);//私有化。
~DownloadManager();//私有化。
public:
static DownloadManager& getInstance(const string name);
bool operator==(const DownloadManager& d2);
};
#endif
/**
DownloadManager.cpp
*/
#include "DownloadManager.h"
using namespace std;
DownloadManager* DownloadManager::sInstance=0;
pthread_mutex_t DownloadManager::mutex=PTHREAD_MUTEX_INITIALIZER;
bool DownloadManager::destroyed=false;
DownloadManager::DownloadManager(string name):mName(name){
}
DownloadManager::~DownloadManager(){
sInstance=0;
destroyed=true;
}
DownloadManager& DownloadManager::getInstance(const string name){
if(sInstance!=NULL){
if(destroyed)
throw runtime_error("dead ref .");
}else{
pthread_mutex_lock(&mutex);
if(!sInstance){
static DownloadManager locInstance(name);
sInstance=&locInstance;
}
pthread_mutex_unlock(&mutex);
}
return *sInstance;
}
bool DownloadManager::operator==(const DownloadManager& d2){
return this->mName==d2.mName;
}
/**
main.cpp
*/
#include "DownloadManager.h"
using namespace std;
int main(){
time_t t=time(NULL);
char* tim=ctime(&t);
cout<<tim<<endl;
{
bool b=DownloadManager::getInstance("lch")==DownloadManager::getInstance("zs");
if(b)
cout<<"equal"<<endl;
}
return 0;//到此进程关闭,回收对象。
}