对象模式所属类别简介-对象性能模式
面向对象很好的解决了“抽象”的问题,但是不可避免要付出一定的代价,虚函数会占用内存信息但是一般都可以忽略不计。不过有些情况还是需要注意。对象性能模式包括:singleton、flyweight
对象性能当前模式简介动机-Singleton
允许new一次
需求
只允许一个对象new
设计一
无
需求更改
无
设计一更改版本
无
违反原则
无
设计二
#include "stdafx.h"
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *m_instance;
void test() { std::cout << "test" << std::endl; }
static Singleton *getInstant();
private:
Singleton(){ };
};
Singleton* Singleton::m_instance = NULL;
//单线程版本、线程非安全版本
//如果是两个线程,可能new2次 单线程使用
Singleton* Singleton::getInstant()
{
if (m_instance == NULL)
{
m_instance = new Singleton;
}
return m_instance;
}
//线程安全版本,但锁的代价过高
//返回m_instance是读操作 写才要锁,读不用 多线程并发量低可以用这个
//Singleton* Singleton::getInstance() {
// Lock lock;
// if (m_instance == NULL) {
// m_instance = new Singleton();
// }
// return m_instance;
//}
//双检查版本-不推荐使用
//New默认顺序是分配内存,构造,把内存地址给m_instance
//但是指令层可能会打乱顺序(reorder) ,可能是分配内存,给内存地址,构造。
//比如线程1进行到new阶段,刚好只分配了内存,把内存给了m_instance,线程2进来不为空,返回了m_instance,但是这个m_instance还不能使用....编译器的问题
//Singleton* Singleton::getInstance() {
// if (m_instance == NULL){
// Lock lock;
// if (m_instance == NULL) {
// m_instance = new Singleton();
// }
// }
// return m_instance;
//}
int main()
{
Singleton *t = Singleton::getInstant();
t->test();
return 0;
}
设计二更改版本
设计二比设计一区别
模式定义
保证类仅有一个实例,并提供一个该实例的访问点。
模式结构
要点总结
1.不能支持拷贝构造函数和clone
class Singleton
{
public:
static Singleton *m_instance;
void test() { std::cout << "test" << std::endl; }
static Singleton *getInstant();
private:
//C98
Singleton(){ };
Singleton(Singleton&){}; //不允许拷贝
Singleton& operator=(const Singleton&){};//不允许拷贝
//C11
//Singleton()=default;
//Singleton(const Singleton&)=delete;
//Singleton& operator=(const Singleton&)=delete;
};
2.可以设置构造函数为protected允许子类派生