(三)Singleton模式

//单体模式保证程序中一个类只有一个唯一的实例。通过将类的构造函数私有化,使得类用户无法得到类的实例;同时类的内部产生一个实例,并保存,然后提供一个接口,返回这个唯一的实例
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值