标签:
单例模式:
确保一个类只有一个实例化的对象并且提供了一个访问这个对象的方法。
UML图:
主要包括:
#include <iostream> class Singleton { public: //这里要将这个方法定义成静态的 static Singleton * getInstance(); private: Singleton() { } private: //静态成员函数只能操作静态成员变量,所以instance也应该是静态的 static Singleton * instance; }; //静态成员变量的初始化 Singleton * Singleton::instance=NULL; Singleton * Singleton::getInstance() { if(instance==NULL) instance=new Singleton(); return instance; } int main() { Singleton *s1=Singleton::getInstance(); Singleton *s2=Singleton::getInstance(); if(s1==s2) std::cout<<"s1 and s2 are the same object"<<std::endl; return 0; }
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string> #include <vector> using namespace std; class LoadBalancer { public: static LoadBalancer * getInstance(); string getServer() { int i=rand()%5; return servers[i]; } private: LoadBalancer() { servers.push_back("server I"); servers.push_back("server II"); servers.push_back("server III"); servers.push_back("server IV"); servers.push_back("server V"); } private: static LoadBalancer * instance; vector<string> servers; }; LoadBalancer * LoadBalancer::instance=NULL; LoadBalancer * LoadBalancer::getInstance() { if(instance==NULL) instance=new LoadBalancer(); return instance; } int main() { srand(time(0)); LoadBalancer * load1=LoadBalancer::getInstance(); LoadBalancer * load2=LoadBalancer::getInstance(); cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; cout<<load1->getServer()<<endl; delete load1; return 0; }
标签:
原文地址:http://blog.csdn.net/u012501459/article/details/46505551