单实例类:保证程序永远能获得同一个Java对象
写一个SingLeton单实例类,从线程安全和性能方面考虑去设计
老方法:
public class Singleton{
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
存在线程安全问题,而且性能不高
改进:
public class Singleton{
private static Singleton instance = null ;
public static synchronized getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
解决了线程安全问题;不用每次都创建对象,只在第一次,而且在需要时才实例化,提高效率