懶漢模式的常規使用

2021-10-04 22:55:36 字數 913 閱讀 2251

設計模式之單例模式

這裡不做模式的分析討論,僅針對使用過的用法進行演示。

最早使用的方法:

.h

#include

classa}

return self;

//返回唯一例項s

}private

:static std:

:mutex m_mutex;

static

a*self;

}

.cpp

//初始化靜態變數

std:

:mutex a

::m_mutex;a*

a::self = nullptr;a:

:a()

a::~

a()

#include 

classa}

return self;

//返回唯一例項s

}private

://在模式內部,定義乙個類成員,利用類的析構特性,刪除自身

class

delete}}

;static std:

:mutex m_mutex;

static

a*self;

static

delete m_delete;

}

//初始化靜態變數

std:

:mutex a

::m_mutex;a*

a::self = nullptr;

//新增對delete的初始化a:

:deletea:

:m_delete;a:

:a()

a::~

a()

單例模式 懶漢模式

在實際應用中,我們往往希望在使用的時候才進行類的載入,而不希望類初始化的時候就進行載入,所以單例模式又有了另外一種實現,懶漢模式 一.延遲載入 如下 public class myobject public static myobject getinstance return myobject 延遲...

餓漢模式和懶漢模式

package pattern.singleton 餓漢式單例類.在類初始化時,已經自行例項化 public class singleton1 已經自行例項化 private static final singleton1 single new singleton1 靜態工廠方法 public st...

懶漢模式與餓漢模式

懶漢模式 加截類的時候就建立物件 class single private static single s new single pubic static single getinstance 餓漢模式 呼叫getinstance 方法時才建立物件 class single private stat...