C++设计模式之单例模式
单例的一般实现比较简单,下面是代码和UML图。由于构造函数是私有的,因此无法通过构造函数实例化,唯一的方法就是通过调用静态函数GetInstance。
代码实现:
Singleton.h
1 #pragma once 2 3 #include <iostream> 4 using namespace std; 5 6 class Singleton 7 { 8 public: 9 static Singleton* GetInstance(const char* name); 10 virtual void Show() {} 11 protected: 12 Singleton() {} 13 private: 14 static Singleton *singleton; //唯一实例的指针 15 16 };
SignletonA.h
1 #pragma once 2 3 #include "Singleton.h" 4 5 class SingletonA: public Singleton 6 { 7 friend class Singleton; //必须为友元类,否则父类无法访问子类的构造函数 8 public: 9 void Show() { cout<<"SingletonA"<<endl; } 10 private: //为保护属性,这样外界无法通过构造函数进行实例化 11 SingletonA() {} 12 };
SignletonB.h
#pragma once #include "Singleton.h" class SingletonB: public Singleton { friend class Singleton; //必须为友元类,否则父类无法访问子类的构造函数 public: void Show() { cout<<"SingletonB"<<endl; } private: //为保护属性,这样外界无法通过构造函数进行实例化 SingletonB() {} };
Singleton.cpp
#include "StdAfx.h" #include "Singleton.h" #include "SignletonA.h" #include "SignletonB.h" Singleton* Singleton::singleton = NULL; Singleton* Singleton::GetInstance(const char* name) { if(singleton == NULL) { if(strcmp(name, "SingletonA") == 0) singleton = new SingletonA(); else if(strcmp(name,"SingletonB") == 0) singleton = new SingletonB(); else singleton = new Singleton(); } return singleton; }
main.cpp
// #include "stdafx.h" #include "Singleton.h" #include <iostream> #include<string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { cout<<"单例模式"<<endl; Singleton *st = Singleton::GetInstance("SingletonA"); st->Show(); system("pause"); return 0; }