Android 設計模式 單例模式

2021-10-03 00:13:03 字數 2055 閱讀 3079

有哪些單例模式:

【實現方式1】:雙重確認–double check lock(dcl)

class singleton 

public void

dosomething()

public static singleton getinstance()

}}return sinstande;

}}

為了減少重複**,可用泛型來優化:

//抽象乙個通用的單例

public

abstract

class

singleton

}}}}

//singleton 建立乙個單例,並實現其create方法

private

static

final singleton

gdefault =

newsingleton

()};

//封裝獲取iactivitymanager單例的函式:

static

public iactivitymanager getdefault()

【實現方式2】:靜態內部類單例

public

class

singleton

public

static singleton getinstance()

//靜態內部類:

private

static

class

singletonholder

}

【實現方式3】:使用容器

public class singletonmanager 

publict static

void

registerservice

(string key, object instance)

} public static object getservice

(string key)

}

private

static

final threadlocal

sthreadinstance =

newthreadlocal

()};

public

static choreographer getinstance()

threadlocal 在同乙個執行緒中獲得同乙個物件,不同執行緒中獲得不同物件

所有程序中只有乙個例項,其實現需要乙個中間人

例如:servicemanager,其中間人是binder驅動。

int

main

(int argc,

char

**ar**)

//驅動中的邏輯:

case binder_set_context_mgr:

if(binder_context_mgr_node !=

null

)//生成mgr結點

binder_context_mgr_node =

binder_new_node

(proc,0,

0);//每個程序都有:

private

static iservicemanger getiservicemanager()

sservicemanager = servicemanagernative.

asinte***ce

(binderinternal.

getcontextobject()

);return sservicemanager;

}//對所有程序來說,servicemanager對應的binder控制代碼都是同乙個:0號binder

sp processstate::

getcontextobject

(const sp

&/*caller*/

)

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

在很多設計模式中,我相信大多數程式猿最早接觸的設計模式就是單例模式啦,當然了我也不例外。單例模式應用起來應該是所有設計模式中最簡單的。單例模式雖然簡單,但是如果你去深深 單例模式,會涉及到很多很多知識,我會繼續更新這篇文章的。單例模式在整個系統中就提供了乙個物件,然後整個系統都去使用這乙個物件,這就...

Android之設計模式一 單例模式

最近寫專案寫的有點心累,寫上幾篇設計模式緩解下心中的煩躁。設計模式是軟體開發人員在軟體開發過程中面臨的一般問題的解決方案。這些解決方案是眾多軟體開發人員經過相當長的一段時間的試驗和錯誤總結出來的。android的設計模式分為三大類 2 結構型模式 介面卡模式,橋接模式,裝飾模式,組合模式,外觀模式,...

精講Android設計模式 單例模式

單例的優點 1.只有乙個例項,節省開銷 2.全域性使用方便,同時避免頻繁建立和銷毀 使用單例的注意點 要避免造成 記憶體洩漏 單例不僅要滿足執行緒安全,還要注意防止序列化產生新物件。如果單例實現了serializable介面,就必須加入如下方法 列舉單例不用這麼做,因為jvm能保障這點 privat...