java设计模式
1、单例模式
- 饿汉模式,在jvm容器启动时就自动创建单例对象
public class Singleton { private static final Singleton INSTANCE = new Singleton(); // Private constructor suppresses // default public constructor private Singleton() {}; public static Singleton getInstance() { return INSTANCE; } }
- 懒汉模式,
public class Singleton { private static volatile Singleton INSTANCE = null; // Private constructor suppresses // default public constructor private Singleton() {}; //Thread safe and performance promote public static Singleton getInstance() { if(INSTANCE == null){ synchronized(Singleton.class){ // When more than two threads run into the first null check same time, // to avoid instanced more than one time, it needs to be checked again. if(INSTANCE == null){ INSTANCE = new Singleton(); } } } return INSTANCE; } }

浙公网安备 33010602011771号