/**
* 单例创建的几种方式
* 1.懒汉式
* 1.1 构造器私有化
* 1.2 声明私有属性
* 1.3 对外提供访问属性的静态方法,确保该对象存在
* @author jhf
*
*/
public class MyJvm {
private static MyJvm instance;
private MyJvm() {
// TODO Auto-generated constructor stub
}
public static MyJvm getInstance() {
if(instance == null) { //提供效率
synchronized(MyJvm.class) {
if(instance == null) { //提供安全
instance = new MyJvm();
}
}
}
return instance;
}
}
/**
* 2.饿汉式
* 2.1 构造器私有化
* 2.2 声明私有属性,并创建对象
* 1.3 对外提供访问属性的静态方法
* @author jhf
*
*/
class MyJvm2 {
//static 类加载时创建
private static MyJvm2 instance = new MyJvm2();
private MyJvm2() {
// TODO Auto-generated constructor stub
}
public static MyJvm2 getInstance() {
return instance;
}
}
/*
* 2.1饿汉式
* 类在使用的时候加载
*/
class MyJvm3 {
//类在使用的时候加载,延缓加载时机
private static class JvmHolder{
private static MyJvm3 instance = new MyJvm3();
}
private MyJvm3() {
}
public static MyJvm3 getInstance() {
return JvmHolder.instance;
}
}