Java单例模式的几种写法


Java单例模式的几种写法
  1. private static final UserService userService = new UserService();   
  2.   
  3.     private UserService() {   
  4.   
  5.     }   
  6.   
  7.     /**  
  8.      * 采取预加载的方式,userService在 classLoader 载入UserService.class 已经声明了对象  
  9.      *   
  10.      * @return  
  11.      */  
  12.     public static UserService getInstance() {   
  13.         return userService;   
  14.     }   
  15.   
  16.     /**  
  17.      * 用了synchronized 多个线程排队的情况比较严重  
  18.      *   
  19.      * @return  
  20.      */  
  21.     // public static synchronized UserService getInstance(){   
  22.     // if(userService==null){   
  23.     // userService = new UserService();   
  24.     // }   
  25.     // return userService;   
  26.     // }   
  27.     /**  
  28.      * 可能会创建多个实例的情况  
  29.      *   
  30.      *   
  31.      */  
  32.     // public static UserService getInstance() {   
  33.     // if (userService == null) {   
  34.     // synchronized (UserService.class) {   
  35.     //   
  36.     // userService = new UserService();   
  37.     // }   
  38.     // }   
  39.     // return userService;   
  40.     //   
  41.     // }   
  42.     // /**   
  43.     // * 通过双检查来判断,当前实例是否为空,第一次创建实例的时候可能会出现排队情况   
  44.     // *   
  45.     // * 创建完实例后,以后不会有排队的情况   
  46.     // *   
  47.     // */   
  48.     // public static UserService getInstance() {   
  49.     // if (userService == null) {   
  50.     // synchronized (UserService.class) {   
  51.     // if (userService == null) {   
  52.     // userService = new UserService();   
  53.     // }   
  54.     // }   
  55.     // }   
  56.     // return userService;   
  57.     //   
  58.     // }   
  59.       

相关内容