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

设计模式——“signleton”

时间:2014-05-16 23:33:42      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

那天别人问了我一个问题,关于单例模式的,由于之前了解的都是蜻蜓点水,所以重新复习了一次重新总结。

单例模式的写法总的来说有5种:懒汉,恶汉,枚举,双重校验锁,静态内部类

懒汉

bubuko.com,布布扣
 1 public class Signleton{     
 2         private static Signleton instance;     
 3         private Signleton(){}      
 4         public static synchronized Sginleton getInstance(){      
 5              if( instance == null ){     
 6                 instance = new Signleton();      
 7              }      
 8              return instance;      
 9         }    
10 }
bubuko.com,布布扣

恶汉:

bubuko.com,布布扣
 1 public class Singleton {  
 2         private Singleton instance = null;  
 3            static {  
 4                instance = new Singleton();  
 5            }  
 6            private Singleton (){}
 7            public static Singleton getInstance() {  
 8                return this.instance;  
 9         }  
10     }  
bubuko.com,布布扣

双重校验锁:

bubuko.com,布布扣
 1 public class Singleton {     
 2             private volatile static Singleton singleton;     
 3             private Singleton (){}      
 4             public static Singleton getSingleton() {     
 5                 if (singleton == null) {     
 6                       synchronized (Singleton.class) {     
 7                           if (singleton == null) {     
 8                               singleton = new Singleton();     
 9                           }    
10                       } 
11                 }            
12                 return singleton;            
13             }    
14     }  
bubuko.com,布布扣

枚举:

1 public enum Singleton {     
2         INSTANCE;            
3         public void whateverMethod() {}     
4     }

静态内部类:

bubuko.com,布布扣
1 public class Singleton {          
2         private static class SingletonHolder {        
3            private static final Singleton INSTANCE = new Singleton();          
4         }             
5         private Singleton (){}           
6         public static final Singleton getInstance() {                 
7             return SingletonHolder.INSTANCE;             
8         }         
9 }  
bubuko.com,布布扣

有兴趣的可以看这篇文章: http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java
the best way to do it is to use:
Since java5 : enum: 
Pre    java5 :other

设计模式——“signleton”,布布扣,bubuko.com

设计模式——“signleton”

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/m-xy/p/3725055.html

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