黑马程序员技术交流社区

标题: 单例模式的两种形式 [打印本页]

作者: suichuan689    时间: 2015-8-29 21:16
标题: 单例模式的两种形式
A:饿汉式
*                  class Single{
*                          private float height;
*                  private Single(){};
*                  private static Single s=new Single();//先初始化对象
*                  public static Single getInstance(){
*                                  return s;
*                  }
*          }
*         
*          B:懒汉式(存在线程安全问题)
*                  class Single{
*                          private float height;
*                          private Single(){};
*                          private static Single s=null;
*                          private static Single getInstance(){
*                                  if(s==null){//双重if判断,在确保线程安全的前提下,提高代码的执行效率
*                                          synchronized(Single.class)//线程安全问题解决方法(上锁)
*                                                  if(s==null){
*                                                                  s=new Single();       
*                               }
*                       }
*                       return s;
*                  }
*            }






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2