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 }
  • 相关阅读:
    2018.11.29 Struts2中拦截器的学习&项目的实际运用
    2018.11.28 OGNL表达式与struts2框架结合的体现---在配置文件中体现(补充)
    信息化战争
    指令周期
    虚拟存储器
    Advice about life
    时间的价值
    计算机病毒的结构
    网上在线考试
    ch03_1_first.jsp
  • 原文地址:https://www.cnblogs.com/mxmbk/p/5101328.html
Copyright © 2011-2022 走看看