1.基本实现
class Singleton
{
public:
static Singleton *Instance()
{
if (!spInstance)
{
spInstance = new Singleton;
}
return spInstance;
}
protected:
Singleton() { }
~Singleton()
{
if (spInstance)
{
delete spInstance;
}
}
private:
static Singleton *spInstance;
};
Singleton *Singleton::spInstance = nullptr;
2.单例模板
singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
template<typename T>
class Singleton
{
public:
static T &Instance()
{
static T sInstance;
return sInstance;
}
private:
Singleton() { }
Singleton(const Singleton &);
Singleton &operator=(const Singleton &);
};
#endif
main.cpp
#include <iostream>
#include "singleton.h"
using namespace std;
class Example
{
public:
Example() { }
~Example() { }
void Print();
};
void Example::Print()
{
cout << "Example.Print()" << endl;
}
int main()
{
Singleton<Example>::Instance().Print();
}
3.改进的单例模板
singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
template<typename T>
class Singleton
{
public:
static T &Instance()
{
static T sInstance;
return sInstance;
}
protected:
Singleton() { }
virtual ~Singleton() { }
private:
Singleton(const Singleton &);
Singleton &operator=(const Singleton &);
};
#endif
main.cpp
#include <iostream>
#include "singleton.h"
using namespace std;
class Example : public Singleton<Example>
{
friend class Singleton<Example>;
public:
void Print();
private:
Example() { }
virtual ~Example() { }
};
void Example::Print()
{
cout << "Example.Print()" << endl;
}
int main()
{
Example::Instance().Print();
}
4.带参数的单例模板
singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#include <utility>
template<typename T>
class Singleton
{
public:
template<typename... Args>
static void CreateInstance(Args&&... args)
{
spInstance = new T(std::forward<Args>(args)...);
}
static T *Instance()
{
return spInstance;
}
static void DestroyInstance()
{
if (spInstance)
{
delete spInstance;
spInstance = nullptr;
}
}
protected:
Singleton() { }
virtual ~Singleton() { }
private:
Singleton(const Singleton &);
Singleton &operator=(const Singleton &);
private:
static T *spInstance;
};
template<typename T>
T *Singleton<T>::spInstance = nullptr;
#endif
main.cpp
#include <iostream>
#include "singleton.h"
using namespace std;
class Example : public Singleton<Example>
{
friend class Singleton<Example>;
public:
void Print();
private:
Example(int i) { member = i; }
virtual ~Example() { }
private:
int member;
};
void Example::Print()
{
cout << "Example.Print(), member = " << member << endl;
}
int main()
{
Example::CreateInstance(3);
Example::Instance()->Print();
Example::DestroyInstance();
}