单例模式是一种常用的软件设计模式,其定义是单例对象的类只能允许一个实例存在。书上都会提到 饿汉式
和 懒汉式
这两种方式。下面具体些一些实现的例子
1、饿汉式,使用静态变量的方式实现。不存在线程同步的问题。在类加载的过程中实例化。
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
2、饿汉式,使用静态代码块的方式实现。和上面没有什么区别。
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
3、懒汉式,存在线程安全问题,多线程的环境下不可使用。
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
4、懒汉式,为解决上面函数存在线程不安全的问题,可以多getInstance()进行同步。
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
5、懒汉式,同样是解决线程不安全的问题,除了对实例化的函数进行同步,还可以使用同步代码块进行双重检测
//优先考虑这种写法
public class Singleton {
private static volatile Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
6、枚举类型实现单例模式。用enum实现Singleton时线程安全,保证单例。使用方法Singleton.INSTANCE.otherMethods();
//优先考虑这种写法
enum Singleton{
INSTANCE;
public void otherMethods(){
System.out.println("Something");
}
}