C++单例模式类
直观易懂
#include <iostream>
template <typename T>
class Singleton {
public:
static T* GetInstence() {
static T * instence = NULL;
if(instence == NULL) {
instence = new T();
}
return instence;
}
protected:
Singleton() = delete;
Singleton(const Singleton<T> &) = delete;
Singleton<T> & operator = (const Singleton<T> &) = delete;
};
class A {
public:
A() {
std::cout << "this is A" << std::endl;
}
};
class B {
public:
B() {
std::cout << "this is B" << std::endl;
}
};
int main() {
A *a = Singleton<A>::GetInstence();
B *b = Singleton<B>::GetInstence();
delete a;
delete b;
return 0;
}