zoukankan      html  css  js  c++  java
  • 举几个单例模式的例子——茴香豆的茴字有几种写法?

    勤加载(饿汉模式)

     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 }
  • 相关阅读:
    Kendo
    过河
    数组分组(简单dp)
    Codeforces Round #604 (Div. 2)(A-E)
    HDU1253
    HDU1026
    linux常用命令(二) --目录操作
    linux常用命令(一)--ls
    hdu 1072
    Codeforces Round #597 (Div. 2)(A-D)
  • 原文地址:https://www.cnblogs.com/niceboat/p/10219958.html
Copyright © 2011-2022 走看看