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

单件模式之C++实现

2009-09-13 18:54 441 查看
SINGLETON---单件
  定义:保证一个类只有一个实例,并提供一个访问他的全局访问点
  使用频率:
  使用情景:
  HappyFather:“乖儿子不许拿这个玩!”
  HappySon:“老爸这个是什么呀? ”
  HappyFather:“这个呢是咱家的户口本,开始呢只有我的户口页,后来增加了你妈的户口页,后来又增加了你的户口页,以后还会增加你儿子的,儿子的孙子的,子子孙孙的。。。。。。”

例:

/*单件模式例子*/
#include<iostream>
using namespace std;

class child
{
public:
static child* GetChildInstance() //获取类的实例
{
if (childInstance == 0)
{
childInstance = new child;
count++;
}
return childInstance;
}

void SetAge(int a) { age = a;}
void SetSex(int s) { sex = s;}
int GetAge()const { return age; }
int GetCount(){ return count;}

private:
child() { cout<<"Singleton child!"<<endl; } //类外无法声明类对象

//只能通过GetChildInstance方法来获得类的实例
static child* childInstance; //用于返回类的唯一实例,因为它为静态,为类所有
int age;
int sex;
static int count;
};

child* child::childInstance = 0;
int child::count = 0;

void main()
{
child *child1; //声明类对象指针
child1 = child1->GetChildInstance(); //得到类实例
child1->SetAge(24);
cout<<"The age of child1 is "<<child1->GetAge()<<endl;

child *child2;
child2 = child2->GetChildInstance();
child2->SetAge(20);
cout<<"The age of child2 is "<<child2->GetAge()<<endl;

cout<<"构造函数仅被调用"<<child1->GetCount()<<"次;"<<endl;
cout<<"结论:child1 和 child2实际上指向统一实例。"<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: