码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2016-11-14 15:30:33      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:ret   运行   应用程序   解决   zed   模式   加锁   运行时   checked   

最简单的实现

    public class Singleton
    {
        private static Singleton instance;
        private Singleton()
        {
            
        }
        
        public static Singleton getInstance()
        {
            if(instance == null)
            {
                instance = new Singleton();
            }
            
            return instance;
        }
            
    }

但是在多线程的情况下有问题,继续改进

 public class Singleton
    {
        private static Singleton instance;
        private Singleton()
        {
            
        }
        
        public static synchronized Singleton getInstance()
        {
            if(instance == null)
            {
                instance = new Singleton();
            }
            
            return instance;
        }
            
    }

  存在问题:通过增加synchronized关键字。但是同步会降低性能

     解决方案:

        1。如果getInstance()的性能对应用程序不是很关键,就什么都别做。
            如果你的应用程序可以接受getInstance()造成的额外负担,就忘了这件事吧。同步如果你的应用程序可以接受getInstance()地方法既简单又有效。但是你必须知道,同步一个方法               可能造成程序执行效率下降100倍,因此,如果将如果你的应用程序可以接受getInstance()的程序使用在频繁的地方,你可能得重新考虑了。

      2.使用"急切"创建实例,而不用延迟实例化的做法
        如果应用程序总是创建并使用单例,或者在创建和运行时方面的负担不太繁重,你可能想要急切创建此单件。

public class Singleton
{
    private static Singleton instance = new Singleton();
    private Singleton()
    {
        
    }
    
    public static synchronized Singleton getInstance()
    {
        return instance;
    }   
}

 

      3.用"双重检查加锁",在getInstance()中减少同步
         利用双重加锁(double-checked locking),首先检查是否实例已经创建了,如果尚未创建,"才"进行同步。这样一来,只有第一次会同步,这正是我们想要的。

public class Singleton
{
    private static volatile Singleton instance;
    private Singleton()
    {
        
    }
    
    public static Singleton getInstance()
    {
        if (instance == null)
        {
            synchronized(Singleton.class)
            {
                instance = new Singleton();
            }
        }
        
        return instance;
    }         
}

 

  

单例模式

标签:ret   运行   应用程序   解决   zed   模式   加锁   运行时   checked   

原文地址:http://www.cnblogs.com/ld-swust/p/6061673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!