单例模式也称为单件模式、单子模式,是使用最广泛的设计模式之一。其意图是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享。
单例模式通过类本身来管理其唯一实例,这种特性提供了解决问题的方法。唯一的实例是类的一个普通对象,但设计这个类时,让它只能创建一个实例并提供对此实例的全局访问。唯一实例类Singleton在静态成员函数中隐藏创建实例的操作。习惯上把这个成员函数叫做Instance(),它的返回值是唯一实例的指针。
示例代码如下:
#include <iostream>
#include <string>
using namespace std;
class Singleton
{
public:
static Singleton *getInstance()
{
//判断是否第一次调用
if(instance == NULL)
{
instance = new Singleton();
}
return instance;
}
void init(int num, string str)
{
a = num;
buf = str;
}
void display()
{
cout << "a = " << a << ", buf = " << buf << endl;
}
//销毁实例,资源回收
void destroy()
{
if(NULL != instance)
{
delete instance;
instance = NULL;
}
}
private:
Singleton()//构造函数为私有
{
}
~Singleton()//析构函数为私有
{
}
//静态数据成员,类中声明,类外必须定义
static Singleton *instance;
int a;
string buf;
};
//静态数据成员,类外定义
Singleton *Singleton::instance = NULL;
int main()
{
Singleton *p1 = Singleton::getInstance();
p1->init(250, "mike");
p1->display();
cout << "\n=============\n";
Singleton *p2 = Singleton::getInstance();
p2->display();
p2->destroy(); //销毁实例
return 0;
}用户访问唯一实例的方法只有getInstance()成员函数。如果不通过这个函数,任何创建实例的尝试都将失败,因为类的构造函数是私有的。getInstance()使用懒惰初始化,也就是说它的返回值是当这个函数首次被访问时被创建的。这是一种防弹设计——所有getInstance()之后的调用都返回相同实例的指针。
单例模式类Singleton有以下特征:
#include <iostream>
#include <string>
using namespace std;
class Singleton
{
public:
static Singleton *getInstance()
{
//判断是否第一次调用
if(instance == NULL)
{
instance = new Singleton();
}
return instance;
}
void init(int num, string str)
{
a = num;
buf = str;
}
void display()
{
cout << "a = " << a << ", buf = " << buf << endl;
}
private:
Singleton()//构造函数为私有
{
}
~Singleton()//析构函数为私有
{
}
//静态数据成员,类中声明,类外必须定义
static Singleton *instance;
int a;
string buf;
//它的唯一工作就是在析构函数中删除Singleton的实例
class Garbo
{
public:
~Garbo()
{
if(NULL != Singleton::instance){
delete Singleton::instance;
Singleton::instance = NULL;
cout << "instance is detele\n";
}
}
};
//定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数
//static类的析构函数在main()退出后调用
static Garbo temp; //静态数据成员,类中声明,类外定义
};
//静态数据成员,类外定义
Singleton *Singleton::instance = NULL;
Singleton::Garbo Singleton::temp;
int main()
{
Singleton *p1 = Singleton::getInstance();
p1->init(250, "mike");
p1->display();
cout << "\n=============\n";
Singleton *p2 = Singleton::getInstance();
p2->display();
return 0;
}版权声明:本博客文章,大多是本人整理编写,或在网络中收集,转载请注明出处!!
原文地址:http://blog.csdn.net/tennysonsky/article/details/48809541