23種設計模式之Singleton模式(三)

往下看了一下,發現單例模式很好理解,直接一起寫了吧!HAHAHA

第一部分:創建型模式

3. Singleton模式

a. 問題

這個對象(類)只能有一個實例,C++(面向對象和麪向過程的結合)的話可以通過設置一個全局變量來實現,如果時純面向對象的Java,就需要Singleton模式來實現了(不會Java,這句話不太懂,-……-),C++當然也可以這樣用啦。

b.基本思想

通過維護static的成員變量來記錄這個唯一的實例,然後通過static的接口函數instance();來創建這個對象,內部加入判斷條件,只能創建一次,然後不要忘記屏蔽默認構造函數。

c.代碼實現

//Singleton.h
#ifndef _SINGLETON_H_ 
#define _SINGLETON_H_
#include <iostream> 
using namespace std;
class Singleton 
{ 
public: 
	static Singleton* Instance();
protected:
	Singleton();     //Singleton不可以被實例化, 屏蔽構造函數
private: 
	static Singleton* _instance;
	//自動釋放
	// GC 機制
    class GC
    {
    public:
        ~GC()
        {
            // 可以在這裏銷燬所有的資源,例如:db 連接、文件句柄等
            if (_instance!= NULL) {
                delete _instance;
                _instance= NULL;
            }
        }
        static GC gc;  // 用於釋放單例
    };
};

//Singleton.cpp
#include "Singleton.h"
#include <iostream> 
using namespace std;
Singleton* Singleton::_instance = 0;      //靜態成員變量初始化

Singleton::Singleton() { cout<<"Singleton...."<<endl; }

Singleton* Singleton::Instance() 
{ 
	if (_instance == 0) { 
		_instance = new Singleton();
	}
	return _instance; 
}

// 主動釋放
static void DestoryInstance()
{
    if (_instance!= NULL) {
        delete _instance;
        _instance= NULL;
    }
}

客戶端

#include "Singleton.h"
#include <iostream> 
using namespace std; 
Singleton::GC Singleton::GC::gc; // 程序結束自動釋放
int main(int argc,char* argv[]) 
{ 
	Singleton* sgn = Singleton::Instance();
	sgn->DestoryInstance();
	return 0;
}

還有多線程問題:https://blog.csdn.net/liang19890820/article/details/61615495種有介紹

d.使用場景

如和Factory模式在一起使用,因爲系統中工廠對象一般來說只要一個。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章