- 定义:单例模式(Singleton Pattern):单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。
- 代码中的三个要点:
- 单例类的构造函数为私有;
- 提供一个自身的静态私有成员变量;
- 提供一个公有的静态工厂方法。
- 下面以单例模式中的懒汉模式(推迟创建对象)为例,说明单例模式:
//Singleton1.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include<string>
class Planet {
private:
Planet(const std::string& name);
std::string m_name;
static Planet* s_pPlanet;//static member must init out of class;except for static const member.
public:
virtual ~Planet();
static Planet* GetInstance(const std::string& name);
std::string Getname();
};
#endif
//Singleton.cpp
#include<cstdio>
#include "Singleton1.h"
Planet* Planet::s_pPlanet = nullptr;
Planet::Planet(const std::string& name) : m_name(name) {}
Planet ::~Planet() {}
Planet* Planet::GetInstance(const std::string& name)
{
if (s_pPlanet == nullptr)
{
s_pPlanet = new Planet(name);
}
return s_pPlanet;
}
std::string Planet::Getname()
{
return m_name;
}
int main()
{
Planet* pPlanet = Planet::GetInstance("Earth");
printf("%s \n", pPlanet->Getname().c_str());
system("pause");
return 0;
}
- 分析:
- 该模式下,由于构造函数是private的,所以不能通过声明对象的方式进行构造函数调用。但可以通过GetInstance函数进行对象构造。
- 该方式通过GetIstance函数创建(new)了对象,但没有对其进行释放,虽然在程序结束后操作系统可以释放它。但不能主动释放对象的程序仍是不健全的。因此有下面的改进。
//Singleton2.h
#ifndef __SINGLETON__H__
#define __SINGLETON_H__
#include<string>
class Planet
{
public:
virtual ~Planet();
static Planet* GetInstance(const std::string& name);
std::string Getname();
private:
Planet(const std::string& name);
std::string m_name;
static Planet* s_pPlanet;
class CGarbo
{
~CGarbo()
{
if (Planet::s_pPlanet != NULL)
{
delete s_pPlanet;
}
}
};
static CGarbo s_Cgarbo;
};
#endif
- 分析:
- 为了解决不能主动释放对象的问题,该方法在在类中添加了一个静态成员s_Cgarbo,该成员类型为类,只提供析构函数(构造函数使用默认构造),析构函数的功能就是释放掉Singleton类对象。由于类静态成员的生命周期为程序结束,所以当程序结束时析构CGarbo对象,调用~CGarbo()函数时会一同将s_pPlanet释放掉。