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 }
  • 相关阅读:
    Show me the Template
    WPF中的Style(风格,样式)
    像苹果工具条一样平滑连续地缩放
    为窗体添加 "最大化","最小化","还原"等 事件
    [CHM]果壳中的XAML(XAML in a Nutshell)
    我的简约播放器
    很好玩的滚动效果
    项目经验分享(上)
    通过mongodb客户端samus代码研究解决问题
    记录数据库执行情况来分析数据库查询性能问题
  • 原文地址:https://www.cnblogs.com/niceboat/p/10219958.html
Copyright © 2011-2022 走看看