单例模式的性能优化

//单例模式 ①
public class Singleton{

    //访问级别设置为private,确保在系统的其他代码不会被实例化
    private Singleton(){}
    
    //声明static,在jvm加载单例类时,单例对象就会被建立
    private static Singleton singletion = new Singleton();

    public static Singleton getInstance(){
        return singleton;
    }
}


//①中,由于jvm在加载单例类时,单例对象就被建立;当单例类在其他代码中扮演了其他的角色时,那么在任何使用这个单例类的地方都会初始化这个单例变量。
//不管是否有被用到。所以,当创建单例很慢时,这种方式就存在不足了。

//解决思路:即在jvm加载单例类时,单例对象没有被建立;当需要使用单例对象时,才建立
//单例模式   ②
//不足:虽然实现了延迟加载功能,但在多线程环境下,耗时要比①高
public class Singleton{
    private Singleton(){}
    
    private static Singleton singleton = null;
    
    //同步,防止多线程环境下创建多个实例
    public static synchronized Singleton getInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        
        return singleton;
    }
}


//单例模式  ③
//当Singleton加载时,不会初始化其内部类;只有在调用getInstance这个方法时,才会加载内部类SingletonHolder,实现了延迟加载的功能,又降低系统性能。
public class Singleton{
    private Singleton(){}
    
    private static class SingletonHolder{
        private static Singleton instance = new Singleton();    
    }
    
    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }
}
posted @ 2014-07-24 10:46  爱生活者wmmang  Views(1176)  Comments(0Edit  收藏  举报