#pragma once
namespace utility
{
// 需要拼接一下命名空间 utility
#define SINGLETON(x) (friend class utility::##Singleton<x>);
template <typename T>
class Singleton
{
public:
static T* instance()
{
if (m_instance == nullptr)
{
m_instance = new T();
}
return m_instance;
}
private:
Singleton(){}
Singleton(const Singleton<T>&);
Singleton<T>& operator = (const Singleton<T>&);
~Singleton(){}
private:
static T* m_instance;
};
template <typename T>
T* Singleton<T>::m_instance = nullptr;
}
#pragma once
#include "Singleton.h"
#include <iostream>
#include <string>
class A
{
// 声明为友元类Singleton才能创建A的实例
// friend class utility::Singleton<A>;
SINGLETON(A);
public:
void show()
{
std::cout << __FUNCTION__ << m_name << std::endl;
}
private:
A() : m_name(" name"){}
A(const A&);
A& operator = (const A&);
~A(){}
private:
std::string m_name;
};
#include "A.h"
#include "Singleton.h"
using namespace utility;
int main()
{
//1. 类A构造为私有(无法在模板单例类中创建instance实例)使用友元类解决
//2. 对于多线程可能创建多个实例的问题(在主线程中先创建规避掉那种情况即可)
Singleton<A>::instance();
A* instanceA1 = Singleton<A>::instance();
A* instanceA2 = Singleton<A>::instance();
std::cout << "A1: " << instanceA1 << std::endl;
std::cout << "A2: " << instanceA2 << std::endl;
instanceA1->show();
instanceA2->show();
getchar();
return 0;
}