zoukankan      html  css  js  c++  java
  • 单例模式160905

     1 /**
     2  * 单例模式:保证只有一个实例 private Singleton(){};
     3  * 饿汉式:先创建 private static final Singleton INSTANCE = new Singleton(); 用的时候调用 public static Singleton getInstance(){return INSTANCE;}
     4  * 懒汉式:用的时候创建实例。
     5  *         synchronized在方法内,则主要double-check;
     6  *         同步在方法上 public static synchronized Singleton getInstance(){ if(instanceLazy==null) instanceLazy=new Singleton();return instanceLazy;}
     7  * 静态代码块:
     8  *         static{ instanceStaticBlock = new Singleton();}
     9  * 静态内部类:
    10  *         private static class SingletonHolder{ public static final INSTANCE_STATIC_CLASS=new Singleton();}
    11  * 枚举:
    12  *         public enum SingletonEnum{INSTANCE;}
    13  */
    14 public class Singleton implements Serializable{
    15     private Singleton(){};  // 私有化构造方法,外部无法创建本类 
    16     // 饿汉式
    17     private static final Singleton INSTANCE = new Singleton();
    18     public static Singleton getInstanceEager(){ return INSTANCE; }
    19     // 懒汉式
    20     private static volatile Singleton instanceLazy = null;
    21     public static Singleton getInstanceLazy1(){
    22         if(instanceLazy == null){
    23             synchronized(Singleton.class){
    24                 if(instanceLazy == null){
    25                     instanceLazy = new Singleton();
    26                 }
    27             }
    28         }
    29         return instanceLazy;
    30     }
    31     public static synchronized Singleton getInstanceLazy2(){
    32         if(instanceLazy == null){
    33             instanceLazy = new Singleton();
    34         }
    35         return instanceLazy;
    36     }
    37     // 静态代码块
    38     private static Singleton instanceStaticBlock = null;
    39     static{
    40         instanceStaticBlock = new Singleton();
    41     }
    42     public static Singleton getInstanceStaticBlock(){ return instanceStaticBlock; }
    43     // 静态内部类
    44     private static class SingletonHolder{ public static final Singleton INSTANCE = new Singleton(); }
    45     public static Singleton getInstanceStaticClass(){ return SingletonHolder.INSTANCE; }
    46     
    47     // 砖家建议:功能完善,性能更佳,不存在序列化等问题的单例 就是 静态内部类 + 如下的代码
    48     private static final long serialVersionUID = 1L;
    49     protected Object readResolve(){ return getInstanceStaticClass(); }
    50 }
    51 //枚举
    52 enum SingletonEnum{
    53     INSTANCE;
    54 }
  • 相关阅读:
    openfl使用64位的ndk时,编译报错的问题!
    Haxe是何物?
    jsp中如何判断el表达式中的BigDecimal==0
    如何在springmvc的请求过程中获得地址栏的请求
    【原创】【滑块验证码】
    【原创】【aes加密】
    【原创】【qrcodejs2】生成二维码
    【原创】【ueditor】监听内容
    【原创】【ueditor】内容过多时 菜单控件遮挡页面
    js杂谈
  • 原文地址:https://www.cnblogs.com/wangziqiang/p/5841784.html
Copyright © 2011-2022 走看看