您的位置:首页 > 编程语言 > C语言/C++

Head First 设计模式 (五) 单件模式(Singleton pattern) C++实现

2013-04-11 11:15 525 查看
单件模式确保一个类只有一个实例,并提供一个全局访问点。

确定在性能和资源上的限制,然后小心地选择适当的方案来实现单件,以解决多线程的问题。

代码链接:点击打开链接

单件模式类图



源代码:

#ifndef CHOCOLATEBOILER_H
#define CHOCOLATEBOILER_H

#include<iostream>

class ChocolateBoiler
{
private:
ChocolateBoiler()
{
empty = true;
boiled = false;
}
~ChocolateBoiler()
{
uniqueInstance = 0;
}
ChocolateBoiler( const ChocolateBoiler& );
void operator=( const ChocolateBoiler& );
public:
static ChocolateBoiler * getInstance()
{
if(uniqueInstance==0)
{
std::cout << "Creating unique instance of Chocolate Boiler" << std::endl;
uniqueInstance = new ChocolateBoiler();
}
std::cout << "Returning instance of Chocolate Boiler"<< std::endl;
return uniqueInstance;
}
void fill()
{
if(isEmpty())
{
empty = false;
boiled =false;
}
}

void drain()
{
if(!isEmpty() && isBoiled())
{
empty = true;
}
}

void boil()
{
if(!isEmpty() && !isBoiled())
{
boiled = true;
}
}
bool isEmpty()
{
return empty;
}

bool isBoiled()
{
return boiled;
}
protected:
private:
bool empty;
bool boiled;
static ChocolateBoiler* uniqueInstance;
};

#endif // CHOCOLATEBOILER_H


测试代码:

#include "ChocolateBoiler.h"

ChocolateBoiler* ChocolateBoiler::uniqueInstance = 0;
int main()
{
ChocolateBoiler* boiler = ChocolateBoiler::getInstance();
boiler->fill();
boiler->boil();
boiler->drain();

ChocolateBoiler *boiler2= ChocolateBoiler::getInstance();
if(boiler == boiler2)
std::cout<<"Got same boiler"<<std::endl;
else
std::cout<<"Got different boler"<<std::endl;

return 0;
}


测试结果如下:



原创转载注明出处
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: