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.控制数据的共享

  • 相关阅读:
    IOS总结_无需自己定义UITabbar也可改变UITabbarController的背景和点击和的颜色
    破解中国电信华为无线猫路由(HG522-C)自己主动拨号+不限电脑数+iTV
    HDUJ 2074 叠筐 模拟
    CSRF——攻击与防御
    Ant命令行操作
    C#软件开发实例.私人订制自己的屏幕截图工具(七)加入放大镜的功能
    qemu-kvm-1.1.0源代码中关于迁移的代码分析
    FileSystemWatcher使用方法具体解释
    configure交叉编译
    海量图片存储策略
  • 原文地址:https://www.cnblogs.com/tp123/p/6475450.html
Copyright © 2011-2022 走看看