好吧, 第一种单例, 来瞧瞧:
#include <iostream>
using namespace std;
class A
{
private:
A() // 之所以设置为private, 是因为为了防止外部直接生成对象
{
cout << "A" << endl;
}
public:
// 看到这种单例, 也是醉了。 不管咋样, 又多知道了一种方式
static A* getInstance()
{
static A a;
return &a;
}
void print()
{
cout << "hello world" << endl;
}
};
int main()
{
A::getInstance()->print();
A::getInstance()->print();
A::getInstance()->print();
return 0;
}
结果:
A
hello world
hello world
hello world
来看看第二个精妙单例:
#include <iostream>
using namespace std;
class CSingleton
{
public:
static int* getInstance();
};
int* CSingleton::getInstance()
{
static int instance;
return &instance;
}
int main()
{
*CSingleton::getInstance() = 1;
cout << *CSingleton::getInstance() << endl;
return 0;
}
在本例中, int是一个单例, 从结果看(结果是1), 也是。 CSingleton这个类本身没有对应的具体对象, 所以CSingleton的构造函数和析构函数都不会被调用。 如上例子是通过CSingleton这个类来管理int这样一个单例对象。 所以, *CSingleton::getInstance()就对应着一个对象, 即为int变量。
我们用类来代替int, 看看:
#include <iostream>
using namespace std;
class A
{
public:
int x;
A()
{
printf("constrct\n");
}
~A()
{
printf("destruct\n");
}
};
class CSingleton
{
public:
static A* getInstance();
};
A* CSingleton::getInstance()
{
static A instance;
return &instance;
}
int main()
{
CSingleton::getInstance()->x = 100;
cout << CSingleton::getInstance()->x << endl;
cout << CSingleton::getInstance()->x << endl;
cout << CSingleton::getInstance()->x << endl;
return 0;
}
这里没有CSingleton对象, 只有A类的对象, 下面的结果可以验证它是一个A对象的单例, 结果:
constrct
100
100
100
destruct
我个人觉得, 这个单例是很精妙的, 通过static变量只初始化一次这个特性, 来实现了单例的“单”! 哈哈。 下面, 我们继续抽象, 用CSingleton模板来管理单例类, 如下:
#include <iostream>
using namespace std;
class A
{
public:
int x;
A()
{
printf("A constrct\n");
}
~A()
{
printf("A destruct\n");
}
};
class B
{
public:
int x;
B()
{
printf("B constrct\n");
}
~B()
{
printf("B destruct\n");
}
};
template <typename T>
class CSingleton
{
public:
static T* getInstance();
};
template <typename T>
T* CSingleton<T>::getInstance()
{
static T instance;
return &instance;
}
int main()
{
CSingleton<A>::getInstance()->x = 100;
cout << CSingleton<A>::getInstance()->x << endl;
cout << CSingleton<A>::getInstance()->x << endl;
cout << CSingleton<A>::getInstance()->x << endl;
CSingleton<B>::getInstance()->x = 200;
cout << CSingleton<B>::getInstance()->x << endl;
cout << CSingleton<B>::getInstance()->x << endl;
cout << CSingleton<B>::getInstance()->x << endl;
return 0;
}
结果:
A constrct
100
100
100
B constrct
200
200
200
B destruct
A destruct
可以, 通过CSingleton模板, 管理到了不同的单例类。