單例模式(Singleton pattern)四種實現

[align=center][size=x-large]PART 1 快速預覽[/size][/align]
[list]
[*][b]單例實現1:經典單例模式(Classic singleton pattern)[/b]
[/list]
[list=1]
[*]實現延遲實例化(Lazy instantiaze);線程不安全(thread-unsafe)
[*]可用來學習單例模式思想,但是因爲線程不安全,所以[color=red]不建議使用[/color]。
[/list]

/**
* Classic singleton pattern
* @author <a href="mailto:[email protected]">futeng</a>
*/
public class Singleton {
// private static variable
private static Singleton singleton;

// private constructor
private Singleton() {
// do something useful such as initialized data
}

// provides a global point of access to it
public static Singleton getInstance() {
if ( singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}


[list]
[*][b]單例實現2:對方法同步加鎖式單例(Synchronized method singleton pattern)[/b]
[/list]
[list=1]
[*]實現延遲實例化(Lazy instantiaze);線程安全(thread safe);每次訪問都要等候別的線程離開該方法,性能低。
[*]解決了經典單例模式線程不安全的問題,但是性能低下,所以[color=red]不建議使用[/color]。
[/list]

/**
* Synchronized method singleton pattern
* @author <a href="mailto:[email protected]">futeng</a>
*/
public class Singleton {

private static Singleton singleton;

private Singleton() {}

public static synchronized Singleton getInstance() {
if ( singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}


[list]
[*][b]單例實現3:無延遲實例化式單例(Eagerly instantiaze singleton pattern)[/b]
[/list]
[list=1]
[*]非延遲實例化(eagerly instantiaze);線程安全(thread safe);
[*]在類加載的第一時間被初始化,[color=red]大部分場景都可勝任[/color]。丟失了延遲實例化特性,這帶來的遺憾是還未被調用就已經實例化了。
[/list]

/**
* Eagerly singleton pattern
* @author <a href="mailto:[email protected]">futeng</a>
*/
public class Singleton {

private static Singleton singleton = new Singleton();

private Singleton() {}

public static synchronized Singleton getInstance() {
return singleton;
}
}


[list]
[*][b]單例實現4:雙重檢測加鎖式單例(Double-checked locking singleton pattern)[/b]
[/list]
[list=1]
[*]實現延遲實例化(Lazy instantiaze);線程安全(thread safe);
[*]在[color=red]最佳的單例實現[/color],稍微複雜。
[/list]

/**
* Double checked singleton pattern
* @author <a href="mailto:[email protected]">futeng</a>
*/
public class Singleton {

private volatile static Singleton singleton = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
if ( singleton == null) {
synchronized (Singleton. class) {
if ( singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}


[align=center][size=x-large]PART 2 細細品鑑[/size][/align]
發佈了11 篇原創文章 · 獲贊 1 · 訪問量 8783
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章