1. 概念
- 保證一個(gè)類只有一個(gè)實(shí)例
- 并為該實(shí)例提供一個(gè)全局唯一的訪問(wèn)節(jié)點(diǎn)
2. 餓漢式(靜態(tài)常量)
2.1 步驟
- 構(gòu)造器私有化(防止 new)
- 類的內(nèi)部創(chuàng)建對(duì)象
- 向外暴露一個(gè)靜態(tài)的公共方法 -- getInstance()
2.2 代碼示例
示例 - 餓漢式(靜態(tài)常量)
/**
* @Description: 單例模式:餓漢式(靜態(tài)常量)
*/
public class Singleton {
/**
* 構(gòu)造器私有化
*/
private Singleton() {
}
/**
* 在內(nèi)部創(chuàng)建對(duì)象實(shí)例
*/
private final static Singleton INSTANCE = new Singleton();
/**
* 對(duì)外提供公有的靜態(tài)方法
*/
public static Singleton getInstance() {
return INSTANCE;
}
}
public class SingletonTest01 {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
Singleton instance1 = Singleton.getInstance();
System.out.println(instance == instance1);
System.out.println("instance.hashCode= " + instance.hashCode());
System.out.println("instance1.hashCode= " + instance1.hashCode());
}
}
3. 餓漢式(靜態(tài)代碼塊)
3.1 步驟
- 構(gòu)造器私有化(防止 new)
- 類的內(nèi)部創(chuàng)建靜態(tài)成員變量
- 在代碼塊中構(gòu)建成員變量對(duì)象
- 向外暴露一個(gè)靜態(tài)的公共方法 -- getInstance()
3.2 代碼示例
示例 - 餓漢式(靜態(tài)代碼塊)
/**
* @Description: 單例模式:餓漢式(靜態(tài)代碼塊)
*/
public class Singleton02 {
/**
* 構(gòu)造器私有化
*/
private Singleton02() {
}
/**
* 成員變量
*/
private static Singleton02 INSTANCE;
static {
// 在靜態(tài)代碼塊中創(chuàng)建單例對(duì)象
INSTANCE = new Singleton02();
}
/**
* 對(duì)外提供公有的靜態(tài)方法
*/
public static Singleton02 getInstance() {
return INSTANCE;
}
}
public class SingletonTest02 {
public static void main(String[] args) {
Singleton02 instance = Singleton02.getInstance();
Singleton02 instance1 = Singleton02.getInstance();
System.out.println(instance == instance1);
System.out.println("instance.hashCode= " + instance.hashCode());
System.out.println("instance1.hashCode= " + instance1.hashCode());
}
}
4. 優(yōu)缺點(diǎn)
-
優(yōu)點(diǎn)
- 這種寫法比較簡(jiǎn)單,就是在類裝載的時(shí)候就完成實(shí)例化。避免了線程同步問(wèn)題
-
缺點(diǎn)
- 在類裝載的時(shí)候就完成實(shí)例化,沒有達(dá)到Lazy Loading的效果。如果從始至終從未使用過(guò)這個(gè)實(shí)例,則會(huì)造成內(nèi)存的浪費(fèi)
- 這種方式基于classloder機(jī)制避免了多線程的同步問(wèn)題,不過(guò),instance在類裝載時(shí)就實(shí)例化,在單例模式中大多數(shù)都是調(diào)用getinstance方法,但是導(dǎo)致類裝載的原因有很多種,因此不能確定有其他的方式(或者其他的靜態(tài)法)導(dǎo)致類裝載,這時(shí)候初始化instance就沒有達(dá)到lazyloading的效果
5. 結(jié)論
- 這種單例模式可用,但可能造成內(nèi)存浪費(fèi)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。