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

设计模式之单例模式

时间:2015-08-21 23:22:42      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:设计模式

懒汉式

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

加锁

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

双重检查加锁

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

饿汉式

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

设计模式之单例模式

标签:设计模式

原文地址:http://blog.csdn.net/zhou554291911/article/details/47844075

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