前言
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一,这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
单例模式是在内存中 仅会创建一次对象 的设计模式。
简单记录于此,方便自己查阅和回顾。
正文
单例模式实现方式分两种
各有优缺点。
饿汉式
类加载就会导致该单实例对象被创建。如果该类不用或对象太大时会造成资源浪费。
饿汉模式有分静态变量和静态代码块两种,不过本质都是一样的。
静态变量
public class Singleton {
private Singleton() {}
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}
静态代码块
public class Singleton {
private Singleton() {}
private static Singleton instance;
static {
instance = new Singleton();
}
public static Singleton getInstance() {
return instance;
}
}
懒汉式
类加载不会导致该单实例对象被创建,而是首次使用该对象时才会创建,因此多线程时不安全。
方式1
public class Singleton {
private Singleton() {}
private static Singleton instance;
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
方式2
上面如果是多线程,就不安全,使用关键字synchronized,确保多线程安全。
public class Singleton {
private Singleton() {}
private static Singleton instance;
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
虽然上面多线程安全了,但每次获取都用锁了,因此效率比较差。
方式3
下面还有一种双重检查方式,相比上面效率跟高点。
public class Singleton {
private Singleton() {}
private static Singleton instance;
public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
方式4
下面还有一种,使用静态内部类,也是比较推荐的一种方法。
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
参考文章
《》
© 版权声明