java 单例方法_Java-单例模式 - 惊觉
單例模式
單例(Singleton)模式是設計模式之一,最顯著的特點就是一個類在一個JVM中只有一個實例,避免繁瑣的創建銷毀實例。
簡單例子
先看簡單的單例模式實現完整代碼:
Singleton_Test類使用單例模式 ,采用餓漢式方法。
public class Singleton_Test {
private Singleton_Test() {
System.out.println("私有化構造方法");
}
//餓漢式
private static Singleton_Test Instance = new Singleton_Test();
public static Singleton_Test getInstance() {
return Instance;
}
}
再編寫一個測試類Main
public class Main {
public static void main(String args[]) {
Singleton_Test test1 = Singleton_Test.getInstance();
Singleton_Test test2 = Singleton_Test.getInstance();
System.out.println(test1 == test2);
/**
運行結果:
私有化構造方法
true
*/
}
}
逐步分析
1.構造方法私有化
首先,實現單例模式的類,構造方法私有化(private),外部無法實例化(new)該類。
public class Singleton_Test {
private Singleton_Test(){
System.out.println("私有化構造方法");
}
}
無法實例化 Singleton_Test 類。
2.私有靜態類屬性指向實例
所以需要提供一個public static 方法 getInstance(),外部通過這個方法獲取對象,并且由于是 實例化的同一個類,所以外部每次調用都是調用同一個方法,從而實現一個類只有一個實例。
private static Singleton_Test Instance = new Singleton_Test();
//餓漢式
private static Singleton_Test Instance ;
//懶漢式
3.使用公有靜態方法返回實例
返回的都是同一個類,保證只實例化唯一一個類
public static Singleton_Test getInstance(){
return Instance;
}
4.測試類
public static void main(String args[]) {
Singleton_Test test1 = Singleton_Test.getInstance();
Singleton_Test test2 = Singleton_Test.getInstance();
System.out.println(test1 == test2);
/**
運行結果:
私有化構造方法
true
*/
}
輸出結果表示,實例化的是同一個類,并只調用一次構造方法。
單例模式的實現
餓漢式
這種方式無論是否調用,加載時都會創建一個實例。
private static Singleton_Test Instance = new Singleton_Test();
public static Singleton_Test getInstance(){
return Instance;
}
懶漢式
這種方式,是暫時不實例化,在第一次調用發現為null沒有指向時,再實例化一個對象。
private static Singleton_Test Instance ;
public static Singleton_Test getInstance(){
if (Instance == null){
Instance = new Singleton_Test();
}
return Instance;
}
區別
餓漢式的話是聲明并創建對象(他餓),懶漢式的話只是聲明對象(他懶),在調用該類的 getInstance() 方法時才會進行 new對象。
餓漢式立即加載,會浪費內存,懶漢式延遲加載,需要考慮線程安全問題 什么是線程安全/不安全
餓漢式基于 classloader 機制,天生實現線程安全,懶漢式是線程不安全。需要加鎖 (synchronized)校驗等保證單例,會影響效率
總結
構造方法私有化
private Singleton_Test(){}
私有靜態(static)類屬性指向實例
private static Singleton_Test Instance
使用公有靜態方法返回實例
public static Singleton_Test getInstance(){ return Instance;}
轉載自CSDN-專業IT技術社區
版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
總結
以上是生活随笔為你收集整理的java 单例方法_Java-单例模式 - 惊觉的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++学习之路 | PTA乙级—— 10
- 下一篇: 约瑟夫问题C语言加注释,用链表实现约瑟夫