设计模式之单例模式

时间:2022-12-03 20:50:24

静态内部类实现

package com.haxianhe.singleton;

/**
* 静态内部类
*/

public class Singleton5 {
private Singleton5() {

}

private static class InstanceFactory {
public static Singleton5 instance = new Singleton5();
}

public static Singleton5 getInstance() {
return InstanceFactory.instance;
}
}

饿汉模式

package com.haxianhe.singleton;
/**
* 饿汉模式
* */

public class Singleton4 {
private Singleton4() {

}

private static Singleton4 instance = new Singleton4();

public static Singleton4 getInstance() {
return instance;
}
}

懒汉模式(双重锁检测)

package com.haxianhe.singleton;

/**
* 双重锁检测(懒汉模式)
*/

public class Singleton3 {
/* 私有构造方法,防止被实例化 */
private Singleton3() {

}

/* 私有实例变量,防止被引用 */
private static Singleton3 instance = null;

public static Singleton3 getInstance() {
if (instance == null) {
synchronized (instance) {
if (instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}