#include <iostream>
// Singletons in cpp are just like a way to organize a bunch of global variables and static functions
// into one kind of organized blob that is essentially under a single namespace.
// super useful for when we essentially want to have functionality that applies to some kind of
// global set of data, that we just want to potentially repeatedlly reuse.
// for example: a random number generator or a renderer.
// a basic example.
class Singleton
{
public:
Singleton(const Singleton&) = delete;// step 2, delete the copy constructor.
static Singleton& Get()// step 5.
{
return s_Instance;
}
void Function() {}
private:
Singleton() {}//step 1.
float m_Member = 0.0f;
static Singleton s_Instance;// step 3.
};
Singleton Singleton::s_Instance;// step 4.
// useful example: a random number generator class.
class FirstRandom
{
public:
FirstRandom(const FirstRandom&) = delete;
static FirstRandom& Get()
{
return s_Instance;
}
//actual meat here.
float Float() { return m_RandomGenerator; }
private:
FirstRandom() {}
float m_RandomGenerator = 0.5f;
static FirstRandom s_Instance;
};
FirstRandom FirstRandom::s_Instance;
// SecondRandom: without having to call Get().
class SecondRandom
{
public:
SecondRandom(const SecondRandom&) = delete;
static SecondRandom& Get()
{
// once this function gets called for the first time it'll be instantiated,
// basially it's the same like FirstRandom, but looks cleaner.
static SecondRandom s_Instance;
return s_Instance;
}
static float Float() { return Get().IFloat(); }
private:
float IFloat() { return m_RandomGenerator; }//I:internal
SecondRandom() {}
float m_RandomGenerator = 0.5f;
};
// singleton classes can just behave like namespaces.
namespace RandomClass {
static float s_RandomGenerator = 0.5f;
static float Float() { return s_RandomGenerator; }
}
int main(void)
{
Singleton::Get().Function();
//Singleton s = Singleton::Get();//error, copy constructor deleted.
Singleton& s = Singleton::Get();// or auto& s = Singleton::Get();
float first = FirstRandom::Get().Float();
float second = SecondRandom::Float();
std::cout << second << std::endl;
std::cin.get();
}
【Cherno的C++视频】Singletons in C++
最新推荐文章于 2024-09-16 17:46:36 发布