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

    单例模式

    单例模式确保其某一个类只有一个实例,并且自行实例化并向整个系统提供这个实例。这个类叫做单例类。特点:

    1.单例类只能有一个实例

    2.单例类必须自己创建自己唯一的实例。

    3.单例类必须给其他所有对象提供这一实例。

    饿汉式

    用不用都先创建单例类

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

    这种写法不会引发线程安全问题。

    懒汉式

    使用时才去创建

     1 public class LazySingleton {
     2     private static LazySingleton ls = null;
     3     
     4     private LazySingleton(){
     5         
     6     }
     7     
     8     public static LazySingleton getInstance(){
     9         if(ls == null){
    10             return new LazySingleton();
    11         }
    12         return ls;
    13     }
    14 }

     这种写法基本不用,因为是线程不安全的。线程A执行到第9行,然后切换B线程,B线程执行到第9行,也是ls==null,那么两个线程创建了两个对象,这样会出现问题。

    双检锁

    双检锁(DCL),是懒汉式的改进方式。

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

    很明显双检锁是安全的。

    单例应用

     1 public class Runtime {
     2     private static Runtime currentRuntime = new Runtime();
     3 
     4     /**
     5      * Returns the runtime object associated with the current Java application.
     6      * Most of the methods of class <code>Runtime</code> are instance 
     7      * methods and must be invoked with respect to the current runtime object. 
     8      * 
     9      * @return  the <code>Runtime</code> object associated with the current
    10      *          Java application.
    11      */
    12     public static Runtime getRuntime() { 
    13     return currentRuntime;
    14     }
    15 
    16     /** Don't let anyone else instantiate this class */
    17     private Runtime() {}
    18 
    19     ...
    20 }

    单例好处

    1.控制资源的使用

    2.控制资源的产生

    3.控制数据的共享

  • 相关阅读:
    vs2010 怎样设置文本编辑窗口和解决方案资源管理器同步?
    google浏览器如何导出书签
    C#面试题
    Inkscape tricks
    jupyter-notebook kernel died
    matplotlib 显示中文
    Ubuntu+apt-get update时的源
    vscode设置出错, 无法自动补全
    Ubuntu+vscode打不开
    Ubuntu+Firefox总是打不开网页
  • 原文地址:https://www.cnblogs.com/tp123/p/6475450.html
Copyright © 2011-2022 走看看