设计模式
设计模式代表了最佳实践,是软件开发过程中面临一般问题的解决方法
设计模式是一套被反复使用,经过分类,代码设计的经验总结
单例模式
- 单例类保证全局只有一个唯一实例对象
- 单例类提供获取这个唯一实例的接口
不考虑线程安全的一个单例类
#include"stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
using namespace std;
class Singleton
{
public:
//获取唯一对象实例的接口函数
static Singleton* GetInstance()
{
if(_sInstance==NULL)
{
_sInstance=new Singleton;
}
return _sInstance;
}
protected:
Singleton()
:_data(0)
{}
//防拷贝
Singleton(Singleton&);
Singleton&operator=(Singleton&);
static Singleton* _sInstance;
int _data;
};
懒汉模式
#include"stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
using namespace std;
//线程安全版本
//1.懒汉模式
class Singleton
{
public:
//获取唯一对象实例的接口函数
static Singleton* GetInstance()
{
lock();
if(_sInstance==NULL)
{
_sInstance=new Singleton;
}
unlock();
return _sInstance;
}
protected:
Singleton()
:_data(0)
{}
//防拷贝
Singleton(Singleton&);
Singleton&operator=(Singleton&);
static Singleton* _sInstance;
int _data;
};
Singletion* Singleton::_sInstance=NULL;
双重检查版本更加高效
#include"stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
#include<mutex>
using namespace std;
//线程安全版本
//1.懒汉模式
class Singleton
{
public:
//获取唯一对象实例的接口函数
static Singleton* GetInstance()
if(_sInstance==NULL)
{
//lock();
//_mtx.lock();
lock_guard<mutex> lock(_mtx);
if(_sInstance==NULL)
{
_sInstance=new Singleton;
}
//unlock();
//_mtx.unlock();
return _sInstance;
}
}
protected:
Singleton()
:_data(0)
{}
//防拷贝
Singleton(Singleton&);
Singleton&operator=(Singleton&);
static Singleton* _sInstance;
static mutex _mtx;
int _data;
};
mutex Singletion::_mtx;
Singletion* Singleton::_sInstance=NULL;
饿汉模式
#include"stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
#include<mutex>
using namespace std;
//线程安全版本
//1.饿汉模式
class Singleton
{
public:
//获取唯一对象实例的接口函数
static Singleton* GetInstance()
{
assert(_sInstance);
return _sInstance;
}
if(_sInstance==NULL)
{
if(_sInstance==NULL)
{
_sInstance=new Singleton;
}
return _sInstance;
}
}
protected:
Singleton()
:_data(0)
{}
//防拷贝
Singleton(Singleton&);
Singleton&operator=(Singleton&);
static Singleton* _sInstance;
int _data;
};
Singletion* Singleton::_sInstance=new Sigleton();
#include"stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
#include<mutex>
using namespace std;
//线程安全版本
//1.饿汉模式
class Singleton
{
public:
//获取唯一对象实例的接口函数
static Singleton* GetInstance()
{
static Singleton tmp;
return &tmp;
}
if(_sInstance==NULL)
{
if(_sInstance==NULL)
{
_sInstance=new Singleton;
}
return _sInstance;
}
}
protected:
Singleton()
:_data(0)
{}
//防拷贝
Singleton(Singleton&);
Singleton&operator=(Singleton&);
int _data;
};
Singletion* Singleton::_sInstance=new Sigleton();