`

java单例模式的几种写法

    博客分类:
  • java
 
阅读更多

private static final UserService userService = new UserService();

	private UserService() {

	}

	/**
	 * 采取预加载的方式,userService在 classLoader 载入UserService.class 已经声明了对象
	 * 
	 * @return
	 */
	public static UserService getInstance() {
		return userService;
	}

	/**
	 * 用了synchronized 多个线程排队的情况比较严重
	 * 
	 * @return
	 */
	// public static synchronized UserService getInstance(){
	// if(userService==null){
	// userService = new UserService();
	// }
	// return userService;
	// }
	/**
	 * 可能会创建多个实例的情况
	 * 
	 * 
	 */
	// public static UserService getInstance() {
	// if (userService == null) {
	// synchronized (UserService.class) {
	//
	// userService = new UserService();
	// }
	// }
	// return userService;
	//
	// }
	// /**
	// * 通过双检查来判断,当前实例是否为空,第一次创建实例的时候可能会出现排队情况
	// *
	// * 创建完实例后,以后不会有排队的情况
	// *
	// */
	// public static UserService getInstance() {
	// if (userService == null) {
	// synchronized (UserService.class) {
	// if (userService == null) {
	// userService = new UserService();
	// }
	// }
	// }
	// return userService;
	//
	// }
	
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics