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

    1.懒汉-线程不安全

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

    2.懒汉-线程安全(效率很低,99%情况下不需要同步。)

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

    3.饿汉

    1 public class Singleton {  
    2     private static Singleton instance = new Singleton();  
    3     private Singleton (){}  
    4     public static Singleton getInstance() {  
    5     return instance;  
    6     }  
    7 }  

    4.饿汉2

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

    5.静态内部类

    1 public class Singleton {  
    2     private static class SingletonHolder {  
    3     private static final Singleton INSTANCE = new Singleton();  
    4     }  
    5     private Singleton (){}  
    6     public static final Singleton getInstance() {  
    7     return SingletonHolder.INSTANCE;  
    8     }  
    9 }  

    6.枚举

    1 public enum Singleton {  
    2     INSTANCE;  
    3     public void whateverMethod() {  
    4     }  
    5 }  

    7.双重校验锁

     1 public class Singleton {  
     2     private volatile static Singleton singleton;  
     3     private Singleton (){}  
     4     public static Singleton getSingleton() {  
     5     if (singleton == null) {  
     6         synchronized (Singleton.class) {  
     7         if (singleton == null) {  
     8             singleton = new Singleton();  
     9         }  
    10         }  
    11     }  
    12     return singleton;  
    13     }  
    14 }  
  • 相关阅读:
    CentOS 软件安装(yum 和 rpm)
    Ubuntu下的 PPPoE 拨号上网方法
    Vim 去除因为 Unix 和 Windows 换行符不同带来的 ^M 问题
    Python 在 Windows 下安装第三方包,报 Python 未注册的问题解决
    scipy 安装错误及解决
    Python 字典一个易犯的错误
    Linux查看系统信息
    系统更新报错--NO_PUBKEY
    关于直播的技术整理2
    关于直播的技术整理
  • 原文地址:https://www.cnblogs.com/chenglc/p/6922560.html
Copyright © 2011-2022 走看看