概述:主要介绍单例模式是什么,以及单例模式的例子
定义:
一个类的单一实例
外表为类形式的命名空间
一种组织一堆全局变量和静态函数的方式
生命周期:单例的生命周期就是整个程序的生命周期
例子:
#include <iostream>
class Singleton
{
public:
Singleton(const Singleton&) = delete;//删除拷贝构造
static singleton& Get(){
return s Instance;
}
void Function(){
}
private:
singleton(){}
static Singleton s_Instance;
};
Singleton Singleton::s_Instance;
int main()
{
Singleton& instance = Singleton::Get();
//Singleton instance = Singleton::Get();//这样会拷贝了一个对象,也就不是单例模式了
instance.Function();
}
实际一个例子,单例模式写一个随机数生成器
随机数生成器 类
#include <iostream>
class Random
{
public:
Random(const Random&)=delete;
static Random&Get(){
return s Instance;
}
static float Float() {return Get().IFloat();}
private:
float IFloat(){ return m_RandomGenerator; }
Random(){}
float m_RandomGenerator = 0.5f;
static Random s_Instance;
};
Random Random::s_Instance;
int main()
float number = Random::Float();
std::cout <<number <<std::endl;
std::cin.get();
}
另一种方式:实例不需要在类外定义
#include <iostream>
class Random
{
public:
Random(const Random&)=delete;
static Random&Get(){
static Random instance;//这样也可以
return instance;
}
static float Float() {return Get().IFloat();}
private:
float IFloat(){ return m_RandomGenerator; }
Random(){}
float m_RandomGenerator = 0.5f;
static Random s_Instance;
};
int main()
float number = Random::Float();
std::cout <<number <<std::endl;
std::cin.get();
}
写成命名空间!与写成类,所实现的功能是一样的
namespace Randomclass{
static float s_RandomGenerator = 0.5f;
static float Float(){return s_RandomGenerator;}
}
使用类 让代码更有条理
使用命名空间就丧失了赋值变量的能力
注释:
上述资料为个人学习总结笔记