单例模式
1.懒汉式(线程不安全) 不建议使用
public class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }
2.懒汉式(线程安全) 缺点:使用了锁,效率较低 优点:需要使用时才创建对象,节约内存
public class Singleton { private static Singleton instance = null; private Singleton() {} public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }
3.饿汉式 缺点:类加载时就创建对象,浪费内存 优点:没有使用锁,效率高
public class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } }
4.还没学会
浙公网安备 33010602011771号