單例的幾種實(shí)現(xiàn)方式
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號”
優(yōu)質(zhì)文章,第一時間送達(dá)
使用單例需要注意的關(guān)鍵點(diǎn)
1、將構(gòu)造函數(shù)訪問修飾符設(shè)置為private
2、通過一個靜態(tài)方法或者枚舉返回單例類對象
3、確保單例類的對象有且只有一個,特別是在多線程環(huán)境下
4、確保單例類對象在反序列化時不會重新構(gòu)建對象
單例模式的幾種寫法
1.餓漢式(靜態(tài)常量)
class Singleton{
//1.構(gòu)造器私有化,外部不能new
private Singleton(){
}
//2.本類內(nèi)部創(chuàng)建對象實(shí)例
private final static Singleton instance = new Singleton();
//3.提供一個公有的靜態(tài)方法,返回實(shí)例對象
public static Singleton getInstance(){
return instance;
}
}
2、餓漢式(靜態(tài)代碼塊)
class Singleton {
//1.構(gòu)造器私有化,外部不能new
private Singleton() {
}
//2.本類內(nèi)部創(chuàng)建對象實(shí)例
private static Singleton instance;
static { //在靜態(tài)代碼塊中,創(chuàng)建單例對象
instance = new Singleton();
}
//3.提供一個公有的靜態(tài)方法,返回實(shí)例對象
public static Singleton getInstance() {
return instance;
}
}
3、懶漢式(線程不安全)
class Singleton {
private static Singleton instance;
private Singleton() {
}
//提供一個靜態(tài)的公有方法,當(dāng)使用到方法時,才去創(chuàng)建instance
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
4、懶漢式(線程安全,同步方法)
class Singleton {
private static Singleton instance;
private Singleton() {
}
//提供一個靜態(tài)的公有方法,加入同步處理的代碼,解決線程安全問題
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
5、懶漢式(雙重校驗,線程安全,效率較高,推薦使用)
class Singleton {
private static volatile Singleton instance; //volatile保證線程間的可見性
private Singleton() {
}
//提供一個靜態(tài)的公有方法,加入雙重檢查代碼,解決線程安全問題,同時解決懶加載問題
//同時保證了效率,推薦使用
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
6、靜態(tài)內(nèi)部類完成,推薦使用
class Singleton {
private Singleton() {
}
//寫一個靜態(tài)內(nèi)部類,該類中有一個靜態(tài)屬性Singleton
//在調(diào)用getInstance()方法時,靜態(tài)內(nèi)部類才會被裝載,保證了懶加載;同時類加載是線程安全的
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
//提供一個靜態(tài)的公有方法,直接返回SingletonInstance.INSTANCE
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
7、使用枚舉,推薦使用
enum Singleton{
INSTANCE; //屬性
public void doSomething(){
System.out.println("do something");
}
}
————————————————
版權(quán)聲明:本文為CSDN博主「繁臣」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:
https://blog.csdn.net/qq_35028940/article/details/115510972
粉絲福利:Java從入門到入土學(xué)習(xí)路線圖
??????

??長按上方微信二維碼 2 秒
感謝點(diǎn)贊支持下哈 
評論
圖片
表情
