標籤:檢測 public 技術 http sign example 靜態 單例對象 ace
#include <iostream>#include <string>using namespace std;class SignalExample{static SignalExample* c_instance;//將所有的建構函式(建構函式、拷貝構造、賦值重載)都私人化,使外部不能直接建立對象 SignalExample(){}SignalExample();SignalExample(const SignalExample&);SignalExample& operator = (const SignalExample&);//建立一個靜態私人化成員,用來儲存唯一的一個單例對象public://靜態函數 用於建立唯一的單例對象 必須是公有的靜態,這樣在未建立對象之前就可以直接調用static SignalExample* GetInstance();void print();//用於列印對象地址的檢測函數};SignalExample* SignalExample::c_instance = NULL;SignalExample* SignalExample::GetInstance(){//如果已經建立了一個對象,那麼直接返回,如果沒有則調用建構函式if (c_instance == NULL){c_instance = new SignalExample();}return c_instance;}void SignalExample::print(){cout<<"address-->this:"<<this<<endl;}int main(){ SignalExample* s = SignalExample::GetInstance(); SignalExample* s1 = SignalExample::GetInstance(); SignalExample* s2 = SignalExample::GetInstance(); s->print(); s1->print(); s2->print(); return 0;}
#include <iostream>#include <string>#include "Singleton.h"using namespace std;class SignalExample{ friend class Singleton<SignalExample>;//將所有的建構函式(建構函式、拷貝構造、賦值重載)都私人化,使外部不能直接建立對象 SignalExample(){}SignalExample(const SignalExample&);SignalExample& operator = (const SignalExample&);//建立一個靜態私人化成員,用來儲存唯一的一個單例對象public:void print();//用於列印對象地址的檢測函數};class Test{private: friend class Singleton<Test>; Test() { } Test(const Test&) { } Test& operator = (const Test&);public: void print();//用於列印對象地址的檢測函數};void Test::print(){cout<<"address-->this:"<<this<<endl;}void SignalExample::print(){cout<<"address-->this:"<<this<<endl;}int main(){ SignalExample* s = Singleton<SignalExample>::GetInstance(); SignalExample* s1 = Singleton<SignalExample>::GetInstance(); SignalExample* s2 = Singleton<SignalExample>::GetInstance(); Test* s4 = Singleton<Test>::GetInstance(); Test* s3 = Singleton<Test>::GetInstance(); s->print(); s1->print(); s2->print(); s3->print(); s4->print(); return 0;}
#ifndef _SINGLETON_H_#define _SINGLETON_H_template< typename T >class Singleton{ static T* c_instance;public: static T* GetInstance();};template< typename T >T* Singleton<T>::c_instance = NULL;template< typename T >T* Singleton<T>::GetInstance(){ if(c_instance == NULL) { c_instance = new T(); } return c_instance;}#endif
C++單例模式