单例模式Singleton

保证一个类仅有一个实例,并提供一个访问它的全局访问点。

饿汉模式:

类加载就创建对象,没有多线程的安全问题。

缺点:耗费系统资源,有可能创建了实例却没有使用。

  1. /**
  2. * @Author:Lius
  3. * @Date: 2020/7/22 16:32
  4. */
  5. public class HungaryMan {
  6. private final static HungaryMan HUNGARY_MAN = new HungaryMan();
  7. private HungaryMan(){}
  8. public static HungaryMan getInstance(){
  9. return HUNGARY_MAN;
  10. }
  11. }

懒汉模式(线程不安全)

当在使用时才去创建实例,有可能发生线程问题。

  1. /**
  2. * @Author:Lius
  3. * @Date: 2020/7/22 16:36
  4. */
  5. public class LazyManNotSafe {
  6. private static LazyManNotSafe LAZY_MAN_NOT_SAFE;
  7. private LazyManNotSafe(){
  8. System.out.println(Thread.currentThread().getName());
  9. }
  10. public static LazyManNotSafe getLazyManNotSafe() {
  11. if (LAZY_MAN_NOT_SAFE==null){
  12. LAZY_MAN_NOT_SAFE = new LazyManNotSafe();
  13. }
  14. return LAZY_MAN_NOT_SAFE;
  15. }
  16. }

懒汉模式(线程安全)

当在使用时才去创建实例,使用DCL(double check lock)。

  1. /**
  2. * @Author:Lius
  3. * @Date: 2020/7/22 16:42
  4. */
  5. public class LazyManSafe {
  6. private static LazyManSafe LAZY_MAN_SAFE;
  7. private LazyManSafe(){
  8. System.out.println(Thread.currentThread().getName());
  9. }
  10. public static LazyManSafe getLazyManSafe() {
  11. if (LAZY_MAN_SAFE==null){
  12. synchronized (LazyManSafe.class){
  13. if (LAZY_MAN_SAFE==null) {
  14. LAZY_MAN_SAFE = new LazyManSafe();
  15. }
  16. }
  17. }
  18. return LAZY_MAN_SAFE;
  19. }
  20. }