SIngleton单实例类

来源:互联网 发布:小说改编的网络剧 编辑:程序博客网 时间:2024/05/20 17:41

单实例类:保证程序永远能获得同一个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 ;

private static synchronized getInstance(){

if(instance == null){
instance = new Singleton();

}

return instance;

}

}

解决了线程安全问题;不用每次都创建对象,只在第一次,而且在需要时才实例化,提高效率

原创粉丝点击