一、单例模式思维导图
二、具体实现
1.饿汉式
public class Singleton1 {
// 让构造方法私有,别人就没法创建此类的实例了
private Singleton1() {
}
//自己创建这个实例
private static final Singleton1 ME = new Singleton1();
//获取唯一实例
public static Singleton1 getInstance() {
return ME;
}
}
2.普通懒汉式
public class Singleton2 {
private Singleton2() {
}
private static Singleton2 ME;
public static synchronized Singleton2 getInstance() {
// 当一次调用时ME == null为真, 当后续调用时ME == null为假,就不会执行创建对象的操作了
if (ME == null) {
ME = new Singleton2();
}
return ME;
}
}
3.双重检测机制(DCL)懒汉式
public class Singleton3 {
private Singleton3() {
}
private static volatile Singleton3 ME;
public static synchronized Singleton3 getInstance() {
//实例没创建,会进入内部的synchronized代码块
if (ME == null) {
synchronized(Singleton3.class){
//也许有其他线程已经创建实例,所以再判断一次
if (ME == null) {
ME = new Singleton3();
}
}
}
return ME;
}
}
4.静态内部类懒汉式
public class Singleton4 {
private Singleton4() {
}
// holder 拥有, 由静态内部类创建了他的唯一实例
private static class Holder {
static Singleton4 ME = new Singleton4();
}
public static Singleton4 getInstance() {
return Holder.ME;
}
}
5.枚举(饿汉式)
public enum Singleton5 {
ME;
public void m1() {
}
}
三、注意
单例模式由于其简单实现,为初学者所广泛使用,最容易被误用和滥用
1.单例模式不利于单元测试。
2.推荐使用IOC容器(例如Spring)来管理项目中的单例对象,相对而言,IOC容器内是容器内单例,而单例模式是JVM内单例。