1 饿汉模式
/** * 单例模式 1 饿汉模式 * @author hlantian * */ public class Singleton { private static final Singleton sl = new Singleton(); private Singleton() { } public static Singleton getInstance() { return sl; } }
2 懒汉模式
/** * 单例模式2 懒汉模式 * @author hlantian * */ public class Singleton2 { private static Singleton2 instance = null; private Singleton2() {} public static Singleton2 getInstance() { if(instance == null) { instance = new Singleton2(); } return instance; } }