所謂單例,就是整個程序有且僅有一個實例。該類負責創建自己的對象,同時確保只有一個對象被創建。在Java,一般常用在工具類的實現或創建對象需要消耗資源。
特點
- 類構造器私有
- 持有自己類型的屬性
- 對外提供獲取實例的靜態方法
單例模式的多種方式
//最優方式:
//1.在getInstance的方法中沒有鎖,且只有被調用的時候纔會創建Test實例
//2.因爲內部類testContext是private,所以外部無法訪問,無法初始化
//3.只有在調用getInstance纔會初始化這個內部類,保證線程安全
public class Test {
//構造方法私有
private Test(){}
//內部類加載
private static class testContext{
private static Test instrance=new Test();
}
public static Test getInstance(){
return testContext.instrance;
}
}
//第二種 懶漢式 運行到再創建實例 線程不安全
public class Test {
//構造方法私有
private Test(){}
private volatile static Test testContext;
public static Test getInstance(){
if(testContext==null){
testContext=new Test();
}
return testContext;
}
//第三種 餓漢式 先創建實例
public class Test {
//構造方法私有
private Test(){}
private volatile static Test testContext=new Test ();
public static Test getInstance(){
return testContext;
}
}
//第四種 雙鎖單例
public class Test {
//構造方法私有
private Test(){}
private volatile static Test testContext;
public static Test getInstance(){
if (testContext == null) {
synchronized (Test .class) {
if (testContext== null) {
testContext= new testContext();
}
return testContext;
}
}