单例模式的各种实现 package com.fast.DesignPattern.singleton;/** * 单例模式的各种实现 * @author LUSHUIFA242 * */public class UserDao { private UserDao(){}; private static UserDao userDao=null; public static UserDao getInsta
package com.fast.DesignPattern.singleton; /** * 单例模式的各种实现 * @author LUSHUIFA242 * */ public class UserDao { private UserDao(){}; private static UserDao userDao=null; public static UserDao getInstance(){ if (userDao == null) { userDao = new UserDao(); } return userDao; } /** * 加同步处理 * @return */ public static synchronized UserDao getInstance2(){ if (userDao == null) { userDao = new UserDao(); } return userDao; } /** * 双重检查锁定 * @return */ public static UserDao getInstance3() { if (userDao == null) { synchronized (UserDao.class) { if (userDao == null) { userDao = new UserDao(); } } } return userDao; } //============================静态内部类处理开始==================================== /** * 静态内部类处理 * @author LUSHUIFA242 * */ private static class LazyHolder { private static final UserDao INSTANCE = new UserDao(); } public static UserDao getInstance4() { return LazyHolder.INSTANCE; } //============================静态内部类处理结束==================================== //============================枚举内部类处理开始==================================== public static UserDao getInstance5(){ return Singleton.INSTANCE.getInstance(); } private static enum Singleton{ INSTANCE; private UserDao singleton; //JVM会保证此方法绝对只调用一次 private Singleton(){ singleton = new UserDao(); } public UserDao getInstance(){ return singleton; } } //============================枚举内部类处理结束==================================== public static void main(String[] args) { System.out.println(UserDao.getInstance()); System.out.println(UserDao.getInstance2()); System.out.println(UserDao.getInstance3()); System.out.println(UserDao.getInstance4()); System.out.println(UserDao.getInstance5()); } }