/第一种单件模式/ /*#include "iostream.h" class CGlassBottle { public: CGlassBottle(); public: virtual ~CGlassBottle(); public: void OnKnock(){cout<<"OnKnock"<<endl;}; void OnBlow(){cout<<"OnBlow"<<endl;}; void OnRoll(){cout<<"OnRoll"<<endl;}; public: static CGlassBottle * s_GlassBottle ; }; CGlassBottle * CGlassBottle::s_GlassBottle = NULL;//必须对s_ClassBottle进行初始化,详见补充a,b类静态成员说明 CGlassBottle::CGlassBottle() { s_GlassBottle = this; } CGlassBottle::~CGlassBottle() { s_GlassBottle = NULL; } class A//土著人A { public: void UseBottle() { CGlassBottle::s_GlassBottle->OnKnock(); } }; class B//土著人B { public: void UseBottle() { CGlassBottle::s_GlassBottle->OnBlow();//见补充b: } }; int main(int argc, char* argv[]) { // CGlassBottle m_Bottle;//可不对CGlassBottle进行实例化,如进行实例化,则s_GlassBottle不为NULL A a; B b; a.UseBottle(); b.UseBottle(); return 0; }*/ /* 补充:a:一个static成员只有唯一的一个副本,而不像常规的非static成员那样在每个对象里都有一个副本。一个需要访问 的类成员,去不需要针对特定对象去掉用的函数称为static成员函数。 补充:b: 对静态成员引用不必提及任何对象,但应该给成员的名上加作用域的类名称。 */ 第二种单件模式// /*#include "iostream.h" class CGlassBottle { public: CGlassBottle(); public: virtual ~CGlassBottle(); public: void OnKnock(){cout<<"OnKnock"<<endl;}; void OnBlow(){cout<<"OnBlow"<<endl;}; void OnRoll(){cout<<"OnRoll"<<endl;}; private://变为私有成员 static CGlassBottle * s_GlassBottle ; public: static CGlassBottle* GetInstance(); }; CGlassBottle * CGlassBottle::s_GlassBottle = NULL;//详见补充c: CGlassBottle* CGlassBottle::GetInstance() { return s_GlassBottle; } CGlassBottle::CGlassBottle() { s_GlassBottle = this; } CGlassBottle::~CGlassBottle() { s_GlassBottle = NULL; } class A//土著人A { public: void UseBottle() { CGlassBottle::GetInstance()->OnKnock();//见补充c: } }; class B//土著人B { public: void UseBottle() { CGlassBottle::GetInstance()->OnBlow();//见补充b: } }; int main(int argc, char* argv[]) { // CGlassBottle m_Bottle;//可不对CGlassBottle进行实例化,如进行实例化,则s_GlassBottle不为NULL A a; B b; a.UseBottle(); b.UseBottle(); return 0; }*/ /* 补充:c:静态成员(静态函数和静态数据成员)都必须在某个地方另行定义。 */ /第三种模式// #include "iostream.h" #define GetGlassBottle() CGlassBottle::GetInstance() //宏定义,减少代码量 class CGlassBottle { public: CGlassBottle(); public: virtual ~CGlassBottle(); public: void OnKnock(){cout<<"OnKnock"<<endl;}; void OnBlow(){cout<<"OnBlow"<<endl;}; void OnRoll(){cout<<"OnRoll"<<endl;}; private://变为私有成员 static CGlassBottle * s_GlassBottle ; public: static CGlassBottle* GetInstance(); }; CGlassBottle * CGlassBottle::s_GlassBottle = NULL;//详见补充c: CGlassBottle* GetGlassBottle() { return s_GlassBottle; } CGlassBottle::CGlassBottle() { s_GlassBottle = this; } CGlassBottle::~CGlassBottle() { s_GlassBottle = NULL; } class A//土著人A { public: void UseBottle() { GetGlassBottle()->OnKnock();//见补充c: } }; class B//土著人B { public: void UseBottle() { GetGlassBottle()->OnBlow();//见补充b: } }; int main(int argc, char* argv[]) { // CGlassBottle m_Bottle;//可不对CGlassBottle进行实例化,如进行实例化,则s_GlassBottle不为NULL A a; B b; a.UseBottle(); b.UseBottle(); return 0; } ///本人理解单件模式,就是利用C++ static成员的特性,保证一个类所具有的功能被共享,而不用每次都实例化类对象