//第一种实现方法:类的对象只有一个 懒汉
public class Singlton1 {
private static Singlton1 instance;
//让其外部不能再new 对象
private Singlton1(){};
//给外部提供一个方法;得到该类的对象
public static Singlton1 getInstance(){
if(instance==null){
instance = new Singlton1();
}
return instance;
}
}
//第二种实现方法:类的对象只有一个 饿汉
public class Singleton2 {
private static final Singleton2 instance = new Singleton2();
private Singleton2(){};
public static Singleton2 getIntance(){
return instance;
}
}
//第三种实现方法
public class Singleton3 {
private Singleton3(){};
//静态内部类
static class InnerSinglton3{
private static final Singleton3 instance = new Singleton3();
}
public static Singleton3 getInstance(){
return InnerSinglton3.instance;
}
}
//第四种实现方法
public class Singleton4 {
private static Singleton4 instance;
private Singleton4(){};
public static Singleton4 getInstance(){
if(instance==null){ //如果不是null,锁都不用锁
synchronized (Singleton4.class) { //锁模板对象
if(instance==null){ //加锁的过程中不能确保对象是否已创建,安全起见,再判断一次
instance = new Singleton4();
}
}
}
return instance;
}
}