Java单例模式

发布于 2017-06-14 / Java / 0条评论 / 522浏览

Java单例模式的3种实现方法

饿汉模式

public class Singleton { private final static Singleton INSTANCE = new Singleton(); // 私有构造函数 private Singleton() {} // 公开的构造函数 public static Singleton getInstance() { return INSTANCE; } }

懒汉模式

public class Singleton { private static volatile Singleton INSTANCE = null; // 私有构造函数 private Singleton() {} // 线程安全的公开的构造函数 public static Singleton getInstance() { if(INSTANCE == null){ synchronized(Singleton.class){ if(INSTANCE == null){ INSTANCE = new Singleton(); } } } return INSTANCE; } }

枚举实现

public enum Singleton { INSTANCE; public void doSomething() { } } // Call the method from Singleton: Singleton.INSTANCE.doSomething();
评论
站长统计