后端 单例模式

anxing7 · March 25, 2020 · 2 hits

Singleton 单例模式

要点

​ 一,单例类只能有一个实例;

​ 构造器私有化

​ 二,单例类必须自行创建这个实例

​ 含有一个该类的静态变量来保存这个唯一的实例

​ 三,单例类必须自行向整个系统提供整个实例

​ 对外提供获取该实例对象的方法:

​ (1) 直接暴露 (2) 用静态变量的 get 方法获取

饿汉式:直接创建对象,不存在线程安全问题

​ 直接实例化饿汉式(简洁直观)

1
2
3
4
public class {
public static final singleton1 INSTANCE = new singleton1();
private (){}
}

​ 枚举式(最简洁)

​ 枚举类型,表示该类型的对象是有限的几个,可以限定为一个,就成了单例

1
2
3
public enum singleton2{
INSTANCE
}

​ 静态代码块饿汉式(适合复杂实例化)

1
2
3
4
5
6
7
8
public class singleton3{
private static final singleton3 INSTANCE;
static{
INSTANCE = new singleton3();
}

private single3(){}
}

懒汉式:延迟创建对象

​ 线程不安全(适用于单线程)

1
2
3
4
5
6
7
8
9
10
11
public class singleton4{
private singleton4(){}
private static singleton4 instance;

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

​ 线程安全(适用于多线程)

1
2
3
4
5
6
7
8
9
10
11
12
public class singleton5{
private singleton5(){}
private static singleton5 instance;
private static singleton5 getInstance(){
synchronized(singleton5.class){
if(instance == null){
instance = new singleton5();
}
}
return instance;
}
}

​ 静态内部类形式(适用于多线程)

1
2
3
4
5
6
7
8
9
public class singleton6{
private singleton6(){}
private static class Inner{
private static final singleton6 instance = new singleton6();
}
public static singleton6 getInstance(){
return Inner.instance;
}
}
No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.