單例模式懶漢式寫法,單例模式的優化有如下四個方面:java
代碼實現安全
import java.io.Serializable; public class Singleton implements Serializable { //加上volatile關鍵字保證變量的一致性 private volatile static Singleton singleton = null; private Singleton() { if (singleton != null) { throw new RuntimeException("此類爲單例模式,已經被實例化"); } } public static Singleton getInstance() { //外層判斷是防止已經new過了 if (singleton == null) { //加上synchronized關鍵字,保證線程安全 synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }