1 設計模式學習之單例設計模式

2021-10-08 10:17:16 字數 1808 閱讀 8363

一、什麼是單例設計模式?

二、為什麼要使用單例設計模式?

三、如何實現單例設計模式?

缺點 2、懶漢式

public

class

mgr02

public

static mgr02 getinstance()

return instance;

}}

缺點

3、synchronized修飾方法的寫法。-- 解決懶漢式的執行緒安全問題。

public

class

mgr04

private

static mgr04 instance;

// 通過上鎖的方式解決懶漢式執行緒安全問題。只能同時有乙個執行緒訪問以下**。

public

static

synchronized mgr04 getinstance()

return instance;

}}

缺點

4、synchronized**塊的寫法。

public

class

mgr05

private

static mgr05 instance;

public

static mgr05 getinstance()

catch

(interruptedexception e)

instance =

newmgr05()

;}}return instance;

}// 測試

public

static

void

main

(string[

] args)).

start()

;}}}

缺點

5、dcl模式–double check lock雙重檢查鎖

public

class

mgr06

// 加volatile,是因為new 乙個物件的時候,有三步,加了volatile防止這三步發生指令重排序.

private

static

volatile mgr06 instance;

public

static mgr06 getinstance()

catch

(interruptedexception e)

instance =

newmgr06()

;}}}

return instance;

}}

注意

6、靜態內部類的方式

public

class

mgr07

private

static

class

mgr07holder

public

static mgr07 getinstance()

}

7、列舉的寫法

public

enum mgr08

1 設計模式之單例模式

設計模式分為三類型別,共23種 建立型模式 單例模式 抽象工廠模式 原型模式 建造者模式 工廠模式。結構型模式 介面卡模式 橋接模式 裝飾模式 組合模式 外觀模式 享元模式 模式。行為型模式 模板方法模式 命令模式 訪問者模式 迭代器模式 觀察者模式 中介模式 備忘錄模式 直譯器模式 狀態模式 策略...

設計模式(1) 單例設計模式

單例設計模式 定義 確保乙個類只有乙個例項,並且自行例項化,並向整個系統提供這個例項。餓漢式 class single 通過該方法獲得例項物件 public single getinstance 類中其他方法盡量使用static public static void say 通過定義乙個私有訪問許可...

設計模式1單例設計模式

public class sigleton return instance 第二種執行緒加鎖的,太耗時了,執行緒安全是安全,但是太耗時間 這種簡單粗暴的方式不合理,不管他是不是 這種引起的第三種 不推薦使用 public static synchronized sigleton getinstanc...