Java開發模式之單例模式詳細解析

Java開發模式之單例模式詳細解析

單例模式及使用場景

  在Java軟件開發 中,線程池、緩存、日誌對象、對話框、打印機、顯卡的驅動程序對象常被設計成單例。事實上,這些應用都或多或少具有資源管理器的功能。
例如,每臺計算機可以有若干個打印機,但只能有一個 Printer Spooler(單例) ,以避免兩個打印作業同時輸出到打印機中。
再比如,每臺計算機可以有若干通信端口,系統應當集中 (單例)管理這些通信端口,以避免一個通信端口同時被兩個請求同時調用。
總之,選擇單例模式就是爲了避免不一致狀態,避免政出多頭。
  單例模式,在應用的時候在單例對象的類必須保證只有一個實例存在。
( 確保一個類只有一個實例,併爲整個系統提供一個全局訪問點 (向整個系統提供這個實例)。)

  單例三要素:
  1.私有構造
  2.指向自己的實例私有靜態引用
  3.以自己的實例爲返回值靜態的共有的方法

懶漢式(延遲加載)
public class Singleton {
private static Singleton singleton=null;
private Singleton() {}
public static Singleton getInstance() {
if (singleton==null) {
singleton=new Singleton();
}
return singleton;
}

}

餓漢式(立即加載)

public class Singletom {
private static Singletom singletom=new Singletom();
private Singletom() {}
public static Singletom getInstance() {
return singletom;
}
}

總結

  單例模式的優點:
  1、在內存中中只有一個對象,節省內存空間;
  2、避免頻繁的銷燬對象,可以頻繁提高性能;
  3、避免對共享資源多重佔用,簡化訪問;
  4、爲整個系統提供一個全局訪問點。
  單例的使用場景
  1、有狀態的工具了類對象
  2、頻繁訪問數據庫或者文件的對象
測試單例用到hashCode()值

class TestTread extends Thread{br/>@Override
public void run() {
int code = Singletom.getInstance().hashCode();
System.out.println(code);
}
}
public class TestSingleton {
public static void main(String[] args) {
Thread[] t=new Thread[5];
for (int i = 0; i < 5; i++) {
t[i]=new TestTread();
}
for (int i = 0; i < 5; i++) {
t[i].start();
}

 }

}

文章來自:https://www.itjmd.com/news/show-6391.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章