设计模式(一)-单例模式

单例模式是设计模式中比较简单的一种模式,也是使用的比较多的一种模式。

        特别是在某些对象只需要一个时,比如线程池、缓存、日志对象、注册表对象等。

        如果创建了多个,可能会导致很多问题。比如程序行为异常、资源使用过量等。

         

        单例模式确保程序中一个类最多只有一个实例。

        单例模式提供访问这个实例的全局点。

        在Java中单例模式需要:私有构造器、一个静态方法、一个静态变量。

        如果使用多个类加载器,可能会导致单例失效而产生多个实例。

    

        单例模式确保一个类只有一个实例,并提供一个全局的访问点。

        下面为延迟加载的单例模式:

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

        处理多线程:需要将getInstance()变成同步(Synchronized),多线程的问题机会就可以轻松解决。

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

        如果应用程序总是创建并使用单例模式、或者在创建和运行时负担不太繁重,可能急切创建实例:

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

        使用“双重检查加锁”,在getInstance()中减少使用同步:

          /** 
    * volatile 关键字确保当uniqueInstance变量被初始化 
    * 成Singleton实例时,多个线程正确地处理uniqueInstance变量 
    * 
    */  
    ublic class Singleton {  
    private volatile static Singleton uniqueInstance = new Singleton();  
      
    private Singleton() {}  
      
    public static Singleton getInstance() {  
        /**检查实例,不存在则进入同步区**/  
        if(uniqueInstance == null){  
            /**只有第一次才彻底执行下面代码**/  
            synchronized (Singleton.class) {  
                /**进入区块中,再检查一次,如果仍为null,才创建实例**/  
                if(uniqueInstance == null){  
                    uniqueInstance = new Singleton();  
                }  
            }  
        }  
        return uniqueInstance;  

    }  
    欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41016723

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值