最简单的设计模式-----单例模式
C++实现代码:
#include<iostream>
#include<ctime>
#include<random>
#include<algorithm>
using namespace std;
class singleton
{
private:
int i;
singleton()
{
srand(time(NULL));
i = rand() % 10;
}
static singleton *instance;
public:
class ite
{
};
static singleton* get_instance()
{
if(instance == NULL)
instance = new singleton();
return instance;
}
void print()
{
cout << "The unique class! i is "<< i << "\n";
}
};
singleton* singleton::instance = NULL;
int main()
{
singleton::get_instance()->print();
singleton* tmp;
tmp = singleton::get_instance();
tmp->print();
tmp = singleton::get_instance();
tmp->print();
system("pause");
return 0;
}
结果:
The unique class! i is 4
The unique class! i is 4
The unique class! i is 4
请按任意键继续. . .