饿汉式
直接创建实例对象,不管是否需要这个对象,都会创建,线程安全
- 直接实例化
/**
* @Author: daimengying
* @Date: 2019/3/6 09:12
* @Description:饿汉式
*
* 构造器私有
* 自动创建对象,用静态变量保存
* 对外提供实例
*/
public class Singleton1 {
public static final Singleton1 INSTANCE=new Singleton1();
private Singleton1(){
}
}
- 枚举
/**
* @Author: daimengying
* @Date: 2019/3/6 09:20
* @Description:枚举类型:有限的对象
* 枚举类的构造器都是私有
*/
public enum Singleton2 {
INSTANCE
}
- 静态代码块
import java.time.Duration;
import java.time.Instant;
/**
* @Author: daimengying
* @Date: 2019/3/6 09:20
* @Description:静态代码块
*/
public class Singleton3 {
public static final Singleton3 INSTANCE;
static{
Instant statTime = Instant.now(); //当前的时间
INSTANCE=new Singleton3();
System.out.println("单例加载时长:"+ Duration.between(statTime, Instant.now()).toMillis());
}
private Singleton3(){
}
}
懒汉式
/**
* @Author: daimengying
* @Date: 2019/3/6 09:20
* @Description:懒汉式,double check,线程安全
*/
public class Singleton4 {
private static Singleton4 instance;
private Singleton4(){
}
public static Singleton4 getInstance(){
if(instance==null){
synchronized (Singleton4.class){
if(instance==null){
instance=new Singleton4();
}
}
}
return instance;
}
}
/**
* @Author: daimengying
* @Date: 2019/3/6 09:20
* @Description:懒汉式,静态内部类形式
*
* 静态内部类不会自动随着外部类的加载和初始化而初始化,需要单独调用加载
* 因为是在内部类中加载和初始化,因此是线程安全的
*/
public class Singleton5 {
private Singleton5(){
}
private static class Inner{
private static final Singleton5 INSTANCE=new Singleton5();
}
public static Singleton5 getInstance(){
return Inner.INSTANCE;
}
}
网友评论