package swordOffre.gaopengyu;
// 剑指offer2题----实现singleton模式
public class Singleton2 {
// 饿汉模式 贪婪加载
private Singleton2() {
}
private static Singleton2 singleton = new Singleton2();
public static Singleton2 getInstance() {
return singleton;
}
}
// 懒汉模式 单线程
class Singleton {
private Singleton() {
}
private static Singleton singleton;
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
// 懒汉模式 加同步锁
class Singleton3 {
private Singleton3() {
}
private static Singleton3 singleton;
public static Singleton3 getInstance() { // public synchronized static Singleton3 getInstance() 也可
synchronized (Singleton3.class) {
if (singleton == null) {
singleton = new Singleton3();
}
return singleton;
}
}
}
// 懒汉模式 加双重检查锁 效率高
class Singleton4 {
private Singleton4() {
}
private volatile static Singleton4 singleton;
public static Singleton4 getInstance() {
if (singleton == null) {
synchronized (Singleton4.class) {
if (singleton == null) {
singleton = new Singleton4();
}
}
}
return singleton;
}
}
// 懒汉模式 静态内部类形式 利用静态内部类特性
class Singleton5 {
private Singleton5() {
}
private static class SingletonHandler {
private static Singleton5 singleton = new Singleton5();
}
public static Singleton5 getInstance() {
return SingletonHandler.singleton;
}
}
//枚举
enum Singleton6 {
singleton
}
实现singleton模式2
最新推荐文章于 2021-07-08 22:44:16 发布