//单体模式保证程序中一个类只有一个唯一的实例。通过将类的构造函数私有化,使得类用户无法得到类的实例;同时类的内部产生一个实例,并保存,然后提供一个接口,返回这个唯一的实例
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;
//定义Bursh类,该类有一个静态变量,保存自己的唯一实例,有一个静态方法,返回这个实例的指针
class Brush
{
private:
Brush():width_(1),color_("red"){}
unsigned int width_;
string color_;
static Brush *pBrush; //保存自己的唯一实例
public:
void Width(unsigned int width){width_ = width;}
unsigned int Width(){return width_;}
void Color(string color) {color_ = color;}
string Color(){return color_;}
static Brush *Instance() //对外提供实例的接口
{
if ( pBrush == NULL)
{
pBrush = new Brush;
}
return pBrush;
}
};
Brush * Brush::pBrush = NULL; //C++要求静态变量必须在类内部声明,在外部进行定义和初始化
//定义一个使用Brush的类,进行观察
class Artist
{
private:
string name_;
public:
Artist(string name = "NoName"):name_(name){}
void DrawShapes(Brush *pBrush)
{
cout<<"Artist :\t"<<name_<<endl;
cout<<"Draw shapes with brush of width:\t"<<pBrush->Width()<<"and color:\t"<<pBrush->Color()<<endl;
}
};
#endif
#include "singleton.h"
int main()
{
Artist jjp("Jinjupeng");
jjp.DrawShapes(Brush::Instance()->Instance()); //连续两次使用instance()
//更改画笔
Brush::Instance()->Color("black");
Brush::Instance()->Width(20); //先获取一次Instance()将画笔改为black,20
Brush::Instance()->Instance()->Color("Green");
Brush::Instance()->Instance()->Width(100); //调用两次Instance(),将画笔改为Green,100
jjp.DrawShapes(Brush::Instance());
jjp.DrawShapes(Brush::Instance()->Instance()); //两个输出结果都是Green,100,返回的同一个实例。
Brush *pBrush;
jjp.DrawShapes(pBrush->Instance()); //对于静态方法,可以直接用该类型指针进行调用,而不用初始化指针
return 0;
}