基于c++的单列模式实现。

本文详细介绍了下载管理器类的设计与实现,包括私有构造函数、静态实例化、同步互斥锁和多态性操作符重载,以及如何获取实例和比较对象。通过示例代码展示了如何在主函数中初始化和比较两个不同名称的下载管理器实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
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;//到此进程关闭,回收对象。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值