一.懒汉模式
- 单例模式有两种实现方式,懒汉模式和饿汉模式。懒汉模式在类加载时不被初始化。
- 常见的懒汉模式代码
public class LazySingleton {
//定义静态成员变量
private static LazySingleton lazySingleton = null;
//私有构造器,一定要有,防止在其他类中直接使用new创建
private LazySingleton(){}
//静态方法获取实例对象
public static LazySingleton getInstance(){
if(lazySingleton == null){
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
- 单线程中无须考虑线程安全问题,但是在多线程中,需要使用关键字
synchronized
才能保证线程安全。
- 加入关键字
synchronized
的代码
public class LazySingleton {
//定义静态成员变量
private static LazySingleton lazySingleton = null;
//私有构造器
private LazySingleton(){}
//静态方法获取实例对象
public static LazySingleton getInstance(){
synchronized (LazySingleton.class){
if(lazySingleton == null){