• 举几个单例模式的例子——茴香豆的茴字有几种写法?


    勤加载(饿汉模式)

     1 public class EagerSingleton {
     2   
     3   private EagerSingleton() {
     4   }
     5   
     6   private static EagerSingleton instance = new EagerSingleton();
     7   
     8   public static EagerSingleton getInstance() {
     9     return instance;
    10   }
    11 }

    勤加载(static块)

     1 public class StaticBlockSingleton {
     2   
     3   private StaticBlockSingleton() {
     4   }
     5   
     6   private static StaticBlockSingleton instance;
     7   
     8   static {
     9     instance = new StaticBlockSingleton();
    10   }
    11   
    12   public static StaticBlockSingleton getInstance() {
    13     return instance;
    14   }
    15 }

    懒加载(double-checked locking using volatile)

     1 public class DoubleCheckedSingleton {
     2   
     3   private DoubleCheckedSingleton() {
     4   }
     5   
     6   private volatile static DoubleCheckedSingleton instance;
     7   
     8   public static DoubleCheckedSingleton getInstance() {
     9     
    10     if (instance == null) {
    11       synchronized (DoubleCheckedSingleton.class) {
    12         if (instance == null) {
    13           instance = new DoubleCheckedSingleton();
    14         }
    15       }
    16     }
    17     return instance;
    18   }
    19 }

    懒加载(内部静态类)

     1 public class InnerClassSingleton {
     2   
     3   private InnerClassSingleton() {
     4   }
     5   
     6   private static class Holder {
     7     private static InnerClassSingleton instance = new InnerClassSingleton();
     8   }
     9   
    10   public static InnerClassSingleton getInstance() {
    11     return Holder.instance;
    12   }
    13 }

    懒加载(枚举)

     1 public enum EnumSingleton {
     2   
     3   INSTANCE;
     4   
     5   private Singleton instance;
     6   
     7   EnumSingleton() {
     8     instance = new Singleton();
     9   }
    10   
    11   public Singleton getInstance() {
    12     return instance;
    13   }
    14   
    15 }
  • 相关阅读:
    LNMP安装后MYSQL数据库无法远程访问解决
    Ubuntu忘记root密码怎么办?
    composer安装出现proc_open没有开启问题的解决方案
    LNMP搭建环境遇到的N多坑
    lnmp HTTP ERROR 500
    LNMP集成运行(开发)环境的部署
    最新javamail 使用方案,可以异步发送邮件
    vi常用快捷键
    Dom4j解析XML文件
    Multiple markers at this line @Override的解决方法
  • 原文地址:https://www.cnblogs.com/niceboat/p/10219958.html
Copyright © 2020-2023  润新知