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

    一、单例模式:创建一个独一无二的,只能有一个实例对象的入场卷。

    二、实现单例模式步骤

               (1)将类的构造方法设置为私有的。防止外界通过new 形式实例化该类。

               (2)实现返回该类的实例的静态方法。外部只能调用方法或的类的实力对象。

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

    三、存在问题:多线程访问getInstance()方法时,当线程A和线程B第一次访问getInstance()方法时。线程A还未实例化对象。这时线程B已经执行到条件uniqueInstance == null

                结果线程A和线程B会各返回一个实例对象。违反了单例规则。

               解决方法:

                        (1)同步getInstance()方法

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

                        (2)“急切”创建实例,不使用延迟实例化

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

                     (3)“双重检查加锁”(不适用jdk1.4及更早的版本)

     1 public class Singleton {
     2     
     3     private static volatile Singleton uniqueInstance;
     4     
     5     private Singleton(){
     6         
     7     }
     8     public static Singleton getInstance(){
     9         if(uniqueInstance == null){
    10             synchronized(Singleton.class){
    11                 if(uniqueInstance == null){
    12                     uniqueInstance = new Singleton();
    13                 }
    14             }
    15         }
    16         return uniqueInstance;
    17     }
    18 }
  • 相关阅读:
    H50062:meta 定义浏览器的渲染方式
    PHPJN0004:PHP文件上传被安全狗拦截处理
    APP0006- 提示弹窗
    MySQL0002:命令行操作数据库常用命令
    APP0005- data属性的定义
    CSS0018: 字体超长自动隐藏
    JS_0041:JS加载JS文件 异步同步加载js文件
    CSS0017: DIV 上下左右都居中样式
    CSS0016: 多个DIV并排均匀分布 box-sizing
    H50061:html 中引入外部 html 片段
  • 原文地址:https://www.cnblogs.com/mxmbk/p/5101328.html
Copyright © 2011-2022 走看看