整理自网络。
定义:确保一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
类型:创建类模式
类图:
1.类图分为三部分,依次是类名、属性、方法
2.以<<开头和以>>结尾的为注释信息
3.修饰符+代表public,-代表private,#代表protected,什么都没有代表包可见。
4.带下划线的属性或方法代表是静态的。
单例模式应该是23种设计模式中最简单的一种模式了。它有以下几个要素:
- 私有的构造方法
- 指向自己实例的私有静态引用
- 以自己实例为返回值的静态的公有的方法
通过维护一个 static 的成员变量来记录这个唯一的对象实例。通过提供一个 staitc 的接口 instance 来获得这个唯一的实例。需要说明的是,Singleton 不可以被实例化,因此
我们将其构造函数声明为 protected 或者直接声明为 private。代码如下:
//Singleton.h
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};
#endif //~_SINGLETON_H_
//Singleton.cpp
#include "Singleton.h"
#include <iostream>
using namespace std;
Singleton* Singleton::_instance = 0;
Singleton::Singleton()
{
cout<<"Singleton...."<<endl;
}
Singleton* Singleton::Instance()
{
if (_instance == 0)
{
_instance = new Singleton();
}
return _instance;
}
//main.cpp
#include "Singleton.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[])
{
Singleton* pSingleton = Singleton::Instance();
return 0;
}