1.饿汉式
1. 1.直接创建对象,不管你需不需要都会创建 简单直观
要点:
- 1.构造器私有化,因为不能让外面去创建实列
- 2.自己创建,用静态变量保存
- 3.向外提供实列
- 4.为了强调这是一个单列,我们可以用final修饰
public class Singleton1 {
private static final Singleton1 INSTANCE = new Singleton1();
private Singleton1() {
}
}
1. 2. 枚举类型
表示该类对象是有限的几个,我们限定为一个就成了单列了, 枚举类型的构造器默认都是私有化的,且重写了toSting方法
public enum singleton2 {
INSTANCE;
}
1. 3. 使用静态代码块的方式,是1.1的复杂版
主要用于在给对象动态赋值
public class singleton3 {
private static final singleton3 INSTANCE;
private String info;
static {
Properties pro = null;
try {
pro = new Properties();
pro.load(singleton3.class.getClassLoader().getResourceAsStream("sinleton.properties"));
} catch (Exception e) {
e.printStackTrace();
}
INSTANCE = new singleton3(pro.getProperty("info"));
}
private singleton3(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
@Override
public String toString() {
return "singleton3{" +
"info='" + info + '\'' +
'}';
}
public static void main(String[] args) {
System.out.println(singleton3.INSTANCE);
}
}
2. 懒汉式
2.1.延迟创建对象 存在线程安全问题
要点:
- 1.构造器私有化,因为不能让外面去创建实列
- 2.静态变量保存实列
- 3.延迟创建对象
2.2 延迟创建对象
public class singleton4 {
private static volatile singleton4 INSTANCE;
private singleton4() {
}
//调用此方法时再创建对象 DCL双端检索机制保证单列模式安全问题
public static singleton4 getInstance() {
if (INSTANCE == null) {
synchronized (singleton4.class) {
if (INSTANCE == null) {
INSTANCE = new singleton4();
}
return INSTANCE;
}
}
return INSTANCE;
}
public static void main(String[] args) {
Callable<singleton4> ca = () -> singleton4.getInstance();
ExecutorService ex = Executors.newFixedThreadPool(2);
Future<singleton4> s1 = ex.submit(ca);
Future<singleton4> s2 = ex.submit(ca);
try {
System.out.println(s1.get());
System.out.println(s2.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
ex.shutdown();
}
}
2.3 相对使用双端检索机制,我们可以采用 内部静态类来达到线程安全问题
public class singleton5 {
private singleton5() {
}
private static class inner {
private static final singleton5 INSTANCE = new singleton5();
}
//静态内部类不会随着外部类的初始化而初始化,而是在调用此方法的时候才会去初始化
public static singleton5 getInstance() {
return inner.INSTANCE;
}
}
更推荐最后这种