优缺点
1) 这种方式和饿汉式 静态变量的方式类似,只不过将类实例化的过程放在了静态代码块中,也是在类装载的时候,就执行静态代码块中的代码,初始化类的实例,优缺点也是一样的
2)结论:这种单例模式可用,但是可能造成内存浪费
代码语言:javascript复制public class SingletonTest04 {
public static void main(String[] args) {
Singleton04 instance = Singleton04.getInstance();
Singleton04 instance01 = Singleton04.getInstance();
System.out.println(instance == instance01);
System.out.println("instance,hashCode = " instance.hashCode());
System.out.println("instance01,hashCode = " instance01.hashCode());
}
}
class Singleton04 {
private Singleton04() {}
private final static Singleton04 instance;
static {
instance = new Singleton04();
}
public static Singleton04 getInstance(){
return instance;
}
}
// 运行结果
true
instance,hashCode = 1846274136
instance01,hashCode = 1846274136