参考文章:
#pragma once
#include <iostream>
#include <thread>
#include <mutex >
class FSingleton
{
private:
static FSingleton* Instance;
FSingleton() {}
public:
static FSingleton* GetInstance()
{
if (Instance == nullptr)
{
Instance = new FSingleton();
}
return Instance;
}
void Print()
{
std::cout << "This is FSingleton class." << std::endl;
}
};
FSingleton* FSingleton::Instance = nullptr;
class SSingleton
{
private:
static SSingleton* Instance;
SSingleton() {}
public:
static SSingleton* GetInstance()
{
return Instance;
}
void Print()
{
std::cout << "This is FSingleton class." << std::endl;
}
};
SSingleton* SSingleton::Instance = new SSingleton();
class TSingleton
{
private:
class SingleHolder
{
public:
static TSingleton* Instance;
};
private:
TSingleton() {}
public:
static TSingleton* GetInstance()
{
return SingleHolder::Instance;
}
void Print()
{
std::cout << "This is TSingleton class." << std::endl;
}
};
TSingleton* TSingleton::SingleHolder::Instance = new TSingleton();
class FFSingleton
{
private:
static FFSingleton* Instance;
FFSingleton() {}
public:
static std::mutex mtx;
static FFSingleton* GetInstance();
void Print()
{
std::cout << "This is FFSingleton class." << std::endl;
}
};
FFSingleton* FFSingleton::Instance = nullptr;
std::mutex FFSingleton::mtx;
FFSingleton* FFSingleton::GetInstance()
{
if (Instance == nullptr)
{
if (mtx.try_lock())
{
Instance = new FFSingleton();
mtx.unlock();
}
}
return Instance;
}
//SingletonPattern.cpp
#include "SingletonPattern.h"
int main()
{
FSingleton::GetInstance()->Print();
TSingleton::GetInstance()->Print();
SSingleton::GetInstance()->Print();
FFSingleton::GetInstance()->Print();
system("pause");
return 0;
}