1.类加载,自动初始化(程序中最常用)
private static Dog instance = new Dog();
private Dog(){};
public Dog getInstance(){
return instance;
}
2.懒加载 (双重判断,略显复杂)
private static volatile Dog instance;
public Dog getInstance(){
if(instance!=null){
sychronized(this){
if(instance != null){
instance = new Dog();
}
}
}
}
3.利用内部类 (推荐使用)
(JVM加载类,只有一个实例,内部类也就只有一个实例)
private Dog(){}
private static Class DogInner{
private static Dog instance= new Dog();
}
public Dog getInstance(){
return DogInner.instance;
}
4.利用枚举 (枚举无构造函数,所以是线程安全的)
public enum DogEnum{
INSTANCE
}