源碼git地址 https://github.com/dlovetco/designMode
問題提出
確保一個實體類在整個程序運行中只能被實例化一次。即只能有一個該類的對象。
看到這個問題,有一定編程基礎的同學肯定能夠想到用單例模式。本篇博客我就來寫一下單例模式的5種不同的實現方法。
package singleton;
public class Singleton {
public static void main(String[] args) {
}
}
/**
* 懶漢式 所謂懶漢即只有當需要這個對象的時候纔會去生成
*/
class Singleton1 {
private static Singleton1 singleton1;
private Singleton1() {
}
public static Singleton1 getInstance() {
if (singleton1 == null) {
singleton1 = new Singleton1();
}
return singleton1;
}
}
/**
* 餓漢式 所謂餓漢就是即使系統不需要類中已經迫不及待的生成對象等待系統調用了
*/
class Singleton2 {
private static Singleton2 singleton2 = new Singleton2();
private Singleton2() {
}
public static Singleton2 getInstance() {
return singleton2;
}
}
/**
* 考慮到多線程中單例 則需要考慮到鎖機制(只有飽漢式才需要考慮多線程情況)
*
*/
class Singleton3 {
private static Singleton3 singleton3;
private Singleton3() {
}
//不建議這麼寫。在低版本jdk中都不能夠保證正確性
// public static Singleton3 getInstance() {
// if (singleton3 == null) {
// synchronized (Singleton3.class){
// if (singleton3 == null) {
// singleton3 = new Singleton3();
// }
// }
//
// }
// return singleton3;
// }
//取而代之應該用這種簡單的寫法
public static synchronized Singleton3 getSingleton3() {
if (singleton3 == null) {
singleton3 = new Singleton3();
}
return singleton3;
}
}
/**
* 靜態內部類
*/
class Singleton4 {
private Singleton4() {
}
public static Singleton4 getInstance() {
return innerSingleton4.singleton4;
}
private static class innerSingleton4{
private static Singleton4 singleton4 = new Singleton4();
}
}
/**
* 枚舉類 極力推薦這種寫法 簡單暴力不怕反射~~~
*/
enum Singleton5 {
SINGLETON;
}