单例 设计模式
一、单例模式
1,懒汉式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package org1; 2 3 public class Singleton { 4 private static Singleton instance = null; 5 6 private Singleton() {} 7 8 public static Singleton getInstance() { 9 if (instance == null) 10 instance = new Singleton(); 11 12 return instance; 13 } 14 }
2,饿汉式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package org2; 2 3 public class Singleton { 4 private static Singleton instance = new Singleton(); 5 6 private Singleton() {} 7 8 public static Singleton getInstance() { 9 return instance; 10 } 11 }
3,双重锁式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package org3; 2 3 //这个模式将同步内容下方到if内部,提高了执行的效率,不必每次获取对象时都进行同步,只有第一次才同步,创建了以后就没必要了。 4 public class Singleton { 5 private static Singleton instance = null; 6 7 private Singleton() {} 8 9 public static Singleton getInstance() { 10 if (instance == null) { 11 synchronized (Singleton.class) { 12 if (null == instance) { 13 instance = new Singleton(); 14 } 15 } 16 } 17 return instance; 18 } 19 }