設計模式 單例模式 C

2022-04-13 07:23:34 字數 1843 閱讀 8092

一: 餓漢式單例:

靜態區初始化instance,然後通過getinstance返回。這種方式沒有多執行緒的問題,是一種以空間換時間的方式,不管程式用不用,都會構造唯一的例項。

#pragma once

#include

#include "lock.h"

class singleton

};#include "stdafx.h"

#include "singleton.h"

singleton::singleton()

singleton::~singleton()

singleton::singleton(const singleton&)

{}singleton& singleton::operator=(const singleton&)

singleton* singleton::m_pinstance = new singleton();

// designpattern.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include "singleton.h"

#include

using namespace std;

int main()

二: 懶漢式單例:

在需要的時候才建立唯一的例項,可能有多執行緒的問題。下面是採用雙重檢查的方式實現:

2.1 用類的靜態成員的方式

#include

#include "lock.h"

class singleton

unlock();

}return m_pinstance;}};

#include "stdafx.h"

#include "singleton.h"

singleton::singleton()

singleton::~singleton()

singleton::singleton(const singleton&)

{}singleton& singleton::operator=(const singleton&)

singleton* singleton::m_pinstance =null;

// designpattern.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include "singleton.h"

#include

using namespace std;

int main()

2.1 用區域性靜態變數的方式

#pragma once

#include

#include "lock.h"

class singleton

};#include "stdafx.h"

#include "singleton.h"

singleton::singleton()

singleton::~singleton()

singleton::singleton(const singleton&)

{}singleton& singleton::operator=(const singleton&)

// designpattern.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include "singleton.h"

#include

using namespace std;

int main()

設計模式 C 設計模式 單例模式

設計模式 物件導向設計七大原則 設計模式 設計模式概念和分類 設計模式 c 設計模式 單例模式 設計模式 c 設計模式 工廠方法模式 設計模式 c 設計模式 抽象工廠模式 設計模式 c 設計模式 建造者模式 設計模式 c 設計模式 原型模式 作者自用的泛型單例模組 單例模式 singleton pa...

C 設計模式 (單例模式)

單例模式 顧名思義,只有乙個物件例項,即保證乙個類只有乙個物件可以使用。作用類似於乙個全域性變數,可以任意呼叫,但是比全域性變數更容易管理,使用。單例模式也有很多種實現方式 第一種實現方法 h檔案 class csock test public casyncsocket cpp檔案 csock te...

設計模式 單例模式(c )

在gof 設計模式 中,單例模式的定義為 保證乙個類僅有乙個例項,並提供乙個該例項的全域性訪問點。下面是單例模式的c 實現 方案一 建構函式和拷貝建構函式一定要宣告為private 定義static成員 單例指標和獲取單例指標的函式 static單例指標要在類外定義並初始化 實現獲取單例指標的函式時...