上面的章節中,咱們介紹了工廠模式,它是建立型模式的一種。本章咱們將會介紹 單例模式 ,它也是建立型模式的一種。單例模式是咱們比較經常使用的一個設計模式,也是最簡單的一種設計模式。java
介紹:確保在一個jvm中某個類有且只有一個實例。設計模式
類圖:安全
從上面的類圖中,咱們能夠總結出如下幾點:多線程
單例模式的實現方式有8種,下面讓咱們分別來看一看這幾種實現方式的區別。jvm
代碼:函數
public class Singleton { private Singleton() {} private static Singleton singleton = new Singleton(); public static Singleton initSingleton() { return singleton; } }
代碼:spa
public class Singleton { private Singleton() {} private static Singleton singleton; static { singleton = new Singleton(); } public static Singleton initSingleton() { return singleton; } }
import java.util.Objects; public class Singleton { private Singleton() {} private static Singleton singleton; public static Singleton initSingleton() { if (Objects.isNull(singleton)) { singleton = new Singleton(); } return singleton; } }
import java.util.Objects; public class Singleton { private Singleton() {} private static Singleton singleton; public static synchronized Singleton initSingleton() { if (Objects.isNull(singleton)) { singleton = new Singleton(); } return singleton; } }
import java.util.Objects; public class Singleton { private Singleton() {} private static Singleton singleton; public static Singleton initSingleton() { if (Objects.isNull(singleton)) { synchronized (Singleton.class) { singleton = new Singleton(); } } return singleton; } }
import java.util.Objects; public class Singleton { private Singleton() {} private static volatile Singleton singleton; public static Singleton initSingleton() { if (Objects.isNull(singleton)) { synchronized (Singleton.class) { if(Objects.isNull(singleton)) { singleton = new Singleton(); } } } return singleton; } }
public class Singleton { private Singleton() {} public static Singleton initSingleton() { return SingletonInstance.singleton; } public static class SingletonInstance { private static Singleton singleton = new Singleton(); } }
public enum Singleton { INSTANCE; }