单例模式160905
生活随笔
收集整理的這篇文章主要介紹了
单例模式160905
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1 /**
2 * 單例模式:保證只有一個(gè)實(shí)例 private Singleton(){};
3 * 餓漢式:先創(chuàng)建 private static final Singleton INSTANCE = new Singleton(); 用的時(shí)候調(diào)用 public static Singleton getInstance(){return INSTANCE;}
4 * 懶漢式:用的時(shí)候創(chuàng)建實(shí)例。
5 * synchronized在方法內(nèi),則主要double-check;
6 * 同步在方法上 public static synchronized Singleton getInstance(){ if(instanceLazy==null) instanceLazy=new Singleton();return instanceLazy;}
7 * 靜態(tài)代碼塊:
8 * static{ instanceStaticBlock = new Singleton();}
9 * 靜態(tài)內(nèi)部類:
10 * private static class SingletonHolder{ public static final INSTANCE_STATIC_CLASS=new Singleton();}
11 * 枚舉:
12 * public enum SingletonEnum{INSTANCE;}
13 */
14 public class Singleton implements Serializable{
15 private Singleton(){}; // 私有化構(gòu)造方法,外部無(wú)法創(chuàng)建本類
16 // 餓漢式
17 private static final Singleton INSTANCE = new Singleton();
18 public static Singleton getInstanceEager(){ return INSTANCE; }
19 // 懶漢式
20 private static volatile Singleton instanceLazy = null;
21 public static Singleton getInstanceLazy1(){
22 if(instanceLazy == null){
23 synchronized(Singleton.class){
24 if(instanceLazy == null){
25 instanceLazy = new Singleton();
26 }
27 }
28 }
29 return instanceLazy;
30 }
31 public static synchronized Singleton getInstanceLazy2(){
32 if(instanceLazy == null){
33 instanceLazy = new Singleton();
34 }
35 return instanceLazy;
36 }
37 // 靜態(tài)代碼塊
38 private static Singleton instanceStaticBlock = null;
39 static{
40 instanceStaticBlock = new Singleton();
41 }
42 public static Singleton getInstanceStaticBlock(){ return instanceStaticBlock; }
43 // 靜態(tài)內(nèi)部類
44 private static class SingletonHolder{ public static final Singleton INSTANCE = new Singleton(); }
45 public static Singleton getInstanceStaticClass(){ return SingletonHolder.INSTANCE; }
46
47 // 磚家建議:功能完善,性能更佳,不存在序列化等問(wèn)題的單例 就是 靜態(tài)內(nèi)部類 + 如下的代碼
48 private static final long serialVersionUID = 1L;
49 protected Object readResolve(){ return getInstanceStaticClass(); }
50 }
51 //枚舉
52 enum SingletonEnum{
53 INSTANCE;
54 }
?
轉(zhuǎn)載于:https://www.cnblogs.com/wangziqiang/p/5841784.html
超強(qiáng)干貨來(lái)襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的单例模式160905的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: html5,表格与框架综合布局
- 下一篇: Hibernate中二级缓存配置