單例設計模式的二種寫法及執行緒安全的懶漢式寫法

2021-10-01 11:28:38 字數 2330 閱讀 2554

單例模式:

單例模式就是採用了一定的方法,保證了再整個系統當中,對某個類的例項物件都只存在唯一的乙個。

單例模式的餓漢式和懶漢式寫法

餓漢式寫法:餓漢式,顧名思義就是很飢餓的意思一上來就建立物件

public class singletontest1 

}// 餓漢式,一呼叫就拿到改物件

class singletondome1

// 2.宣告當前類的物件為static保證呼叫的是用乙個例項,並初始化物件

public final static singletondome1 singletondome1=new singletondome1();

}

懶漢式寫法:懶漢式,證明就是比較懶,需要在使用的時候在建立

public class singletontest2 

}// 懶漢式,需要使用的時候在拿到改物件

class singletondome2

// 2.宣告當前類的物件為static,不立即建立物件

private static singletondome2 singletondome2=null;

// 3.提供外部能獲取到私有物件的方法,並且需要使用static來修飾,證明是共享的

public static singletondome2 getsingletondome2()

return singletondome2;}}

餓漢式和懶漢式的區別:1.餓漢式的壞處:因為是一呼叫該方法就建立物件,所以導致了物件建立的時間過長。

2.餓漢式的好處:執行緒安全

3.懶漢式的好處:延遲建立物件

4.懶漢式的壞處:執行緒不安全

既然說到懶漢式執行緒不安全那怎麼證明,證明之後怎麼樣來保證在多執行緒的情況下保證他執行緒安全呢?

證明其懶漢式執行緒不安全

public class singletontest2 

};thread thread2=new thread()

};thread1.start();

thread2.start();

}}// 懶漢式,需要使用的時候在拿到改物件

class singletondome2

// 2.宣告當前類的物件為static,不立即建立物件

private static singletondome2 singletondome2=null;

// 3.提供外部能獲取到私有物件的方法,並且需要使用static來修飾,證明是共享的

public static singletondome2 getsingletondome2()

catch (interruptedexception e)

singletondome2= new singletondome2();

}return singletondome2;}}

以上測試**的執行結果:二個位址值不一致,證明拿到的物件不一致

懶漢式安全的寫法:新增synchronized鎖

public class singletontest2 

};thread thread2=new thread()

};thread1.start();

thread2.start();

}}// 懶漢式,需要使用的時候在拿到改物件

class singletondome2

// 2.宣告當前類的物件為static,不立即建立物件

private static singletondome2 singletondome2=null;

// 3.提供外部能獲取到私有物件的方法,並且需要使用static來修飾,證明是共享的

public static singletondome2 getsingletondome2()

catch (interruptedexception e)

singletondome2 = new singletondome2();}};

return singletondome2;}}

執行結果:多次執行之後得到的結果還是一致的狀態,證明拿到的物件是同乙個物件

設計模式之單例模式(及七種寫法)

乙個類有且僅有乙個例項,並且自行例項化向整個系統提供 看看下面七種實現方式 public class singleton public static singleton getinstance public class singleton public static singleton getins...

設計模式 單例模式的寫法(基礎寫法和執行緒安全寫法)

單例模式的寫法非常多。先給出一種最基礎的寫法 a種寫法 package singleton public class singletoninstance public static singletoninstance getinstance return msingletoninstance a寫法...

設計模式 單例模式的寫法(基礎寫法和執行緒安全寫法)

單例模式的寫法很多,先給出一種最基礎的寫法 a種寫法 package singleton public class singletoninstance public static singletoninstance getinstance return msingletoninstance a寫法是...