http://www.runoob.com/design-pattern/singleton-pattern.html
介绍
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。由于构造函数是私有的,因此无法通过构造函数实例化,唯一的方法就是通过调用静态函数GetInstance。
应用实例:不能不同打印机同时打印一份文件。
注意:
- 1、单例类只能有一个实例。
- 2、单例类必须自己创建自己的唯一实例。
- 3、单例类必须给所有其他对象提供这一实例。
实现
#include <iostream>
using namespace std;
class Singleton
{
//构造函数私有,这样不会被实例化
private:
Singleton(){}
//创建一个对象
static Singleton* instance ;
public:
static Singleton* getInstance();
void show(){ cout<<"lalala";}
};
Singleton * Singleton::instance = NULL;
Singleton* Singleton::getInstance()
{
if (instance == NULL)
{
instance = new Singleton;
}
return instance;
}
using namespace std;
class Singleton
{
//构造函数私有,这样不会被实例化
private:
Singleton(){}
//创建一个对象
static Singleton* instance ;
public:
static Singleton* getInstance();
void show(){ cout<<"lalala";}
};
Singleton * Singleton::instance = NULL;
Singleton* Singleton::getInstance()
{
if (instance == NULL)
{
instance = new Singleton;
}
return instance;
}
#include "singleton.h"
int main()
{
//Singleton* sing1 = new Singleton;
Singleton* sing1 = Singleton::getInstance();
sing1->show();
getchar();
return 0;
}
int main()
{
//Singleton* sing1 = new Singleton;
Singleton* sing1 = Singleton::getInstance();
sing1->show();
getchar();
return 0;
}