伺服器開發常用設計模式之單例模式

2021-10-09 05:13:11 字數 3277 閱讀 7432

在服務程式開發時,常常會用到單例模式,很多模組的實現只有乙個類例項,為其他模快提供呼叫介面和資料,使用起來方便高效。是我在遊戲伺服器端開發中用的比較多設計模式之一。

由於c++的建構函式不是執行緒安全的。在多執行緒的情況下,為了防止多個執行緒同時建立物件,造成記憶體洩漏,需要我們注意進行處理接下來介紹如何避免記憶體洩漏。

單例模式分為懶漢模式和餓漢模式。

我們可以通過餓漢模式來避免記憶體的洩漏,在單例類定義時就進行類的例項化,就不會存在多個執行緒同時建立物件的情況。這種情況就是用空間換時間,不用在我們使用時再去例項化物件,提前消耗了資源和空間。

下面是通過模板方式實現的單例模式,如果需要用直接繼承使用。

餓漢模式:

#include #include #include using namespace std;

template class singleton

static void delinstance()

} static t& getme()

protected:

singleton() {};

virtual ~singleton() {};

private:

singleton(const singleton&);

singleton& operator=(const singleton&);

private:

static t* m_instance;

};template t* singleton::m_instance = new t();

class testa : public singleton;

~testa() ;

void add()

int get()const

private:

int num;

};class testb : public singleton;

~testb() ;

void add()

int get()const

private:

int num;

};int main()

編譯執行

如果我們需要用單例的時候,繼承一下可以可以用了還有就是如果需要使用時再去例項化物件,就需要使用懶漢模式來實現,我們通過加鎖來避免多個執行緒的競爭。

#include #include #include #include #include using namespace std;

template class singleton

return m_instance;

} static void delinstance()

} static t& getme()

protected:

singleton() {};

virtual ~singleton() {};

private:

singleton(const singleton&);

singleton& operator=(const singleton&);

private:

static pthread_mutex_t mutex;

static t* m_instance;

};templatepthread_mutex_t singleton::mutex = pthread_mutex_initializer;

template t* singleton::m_instance = null;

class testa : public singleton;

~testa() ;

void add()

int get()const

private:

int num;

};class testb : public singleton;

~testb() ;

void add()

int get()const

private:

int num;

};int main()

執行結果:

對於餓漢模式,還有一種方式防止多執行緒構造記憶體洩漏,就是用pthread_once函式來實現。在muduo庫中的單例實現就用pthread_once來實現的。

實現實現如下

#include #include #include #include #include using namespace std;

template class singleton

static void delinstance() }

static t& getme()

protected:

singleton() {};

virtual ~singleton() {};

static void newinstance()

private:

singleton(const singleton&);

singleton& operator=(const singleton&);

private:

static t* m_instance;

static pthread_once_t m_once;

};template pthread_once_t singleton::m_once = pthread_once_init;

template t* singleton::m_instance = null;

class testa : public singleton;

~testa() ;

void add()

int get()const

private:

int num;

};class testb : public singleton;

~testb() ;

void add()

int get()const

private:

int num;

};int main()

執行結果如下:

繼承單例模式 php PHP設計模式之單例模式

單例模式,就是保持乙個物件只存在乙個例項。並且為該唯一例項提供乙個全域性的訪問點 一般是乙個靜態的getinstance方法 單例模式應用場景非常廣泛,例如 資料庫操作物件 日誌寫入物件 全域性配置解析物件 這些場景的共同特徵是從業務邏輯上來看執行期間改物件卻是只有乙個例項 不斷new多個例項會增加...

常用設計模式之 單例模式

概念 從字面意思不難理解,單例模式就是指某個類僅能建立乙個例項。實現 實現單例模式常有兩個誤區 一 看見單例時,最容易聯想到的就是把乙個類的所有屬性以及方法均設為靜態的。初聽上去,這種方法是挺不錯的,但靜態屬性 方法是在類載入時就初始化了,得到自己的空間,這不是我們能夠控制的,當我們程式中有大量這種...

Headfirst java設計模式 單例模式

單例 件 模式 確保乙個類只有乙個例項,並提供乙個全域性訪問點。實現 1.懶漢式 通過延遲例項化實現的單例模式 使用synchronized處理多執行緒訪問,但是效能較差。public class lazyinstantiazesingleton public static synchronized...