单例模式
单例模式确保某一个被要求的类只有一个实例,而且自行实例化并向整个系统提供这个类的实例。
一般情况下有几种形式,常见的面试中的是有两种考验你。也就是常说的懒汉式和饿汉式了。
懒汉式模式
public class Singlon{
private static Singlon instance = null;
//私有的构造方法,这个一定不能丢
private Singlon(){}
public static synchronized Singlon getInstance(){</span>
if(instance == null){
instance = new Singlon();
}
return instance;
}
}
饿汉式模式
public class Singlon{
private static Singlon instance = new Singlon();
private Singlon(){}
public static synchronized Singlon getInstance(){
return instance;
}
}