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

单例模式

时间:2014-09-14 12:41:27      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   div   sp   log   on   c   

 

 1 public class Singleton
 2 {
 3          private static Singleton singleton = new Singleton();//类加载了便初始化该单例对象
 4                                                                                                                                    //之所以称之为饿汉式,因为他太急了
 5          private Singleton()
 6          {
 7          }
 8          public static Singleton getInstance()
 9          {
10                    return singleton;
11          }
12 }

 

 1 public class Singleton
 2 {
 3          private static Singleton singleton;
 4  
 5          private Singleton()
 6          {
 7          }
 8          //注意这里synchronized,保证了线程安全,意思就是每次只有一个线程能够访问该方法
 9          public static synchronized Singleton getInstance()
10          {
11                    if(singleton == null)
12                    {//当singleton要用的时候才初始化,加判断避免重复初始化,保证只new了一次
13                             singleton= new Singleton();
14                    }
15                    return singleton;
16          }
17 }

 

 

 1 public class Singleton
 2 {
 3          private static Singleton instance = null;
 4  
 5          private Singleton()
 6          {
 7                    //dosomething
 8          }
 9  
10          public static Singleton getInstance()
11          {
12                    if(instance == null)
13                    {
14                             synchronized(Singleton.class)//可以思考一下,为什么这样提高效率
15                             {
16                                      if(null == instance)
17                                      {
18                                                instance= new Singleton();
19                                      }
20                             }
21                    }
22                    return instance;
23          }
24 }

 

单例模式

标签:style   blog   color   os   div   sp   log   on   c   

原文地址:http://www.cnblogs.com/friends-wf/p/3970842.html

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