java设计模式之单例模式

  1. 单例模式就是确保某一个类只有一个实例,并且提供一个全局访问点
  2. 特点
    • 只有一个实例。

    • 自我实例化。

    • 提供全局访问点。

  3. 优缺点
    • 优点:由于单例模式只生成了一个实例,所以能够节约系统资源,减少性能开销,提高系统效率,同时也能够严格控制客户对它的访问。

    • 缺点:也正是因为系统中只有一个实例,这样就导致了单例类的职责过重,违背了“单一职责原则”,同时也没有抽象类,这样扩展起来有一定的困难。
  4. 实现方式
    • 饿汉式:线程安全,调用效率高。但是不能延时加载(当类加载的时候,就创建对象)
      class Student
      {
      private Student(){}
      
      private static final Student s = new Student();
      
      public static Student getInstance()
      {
      return s;
      }
      }
    • 懒汉式:由于该模式是在运行时加载对象的,所以加载类比较快,但是对象的获取速度相对较慢,且线程不安全。如果想要线程安全的话可以加上synchronized关键字,但是这样会付出惨重的效率代价。
      class Student
      {
      private Student(){}
      
      private static final Student s = null;
      
      public static Student getInstance()
      {
      if(s==null) 
      {
      //线程1就进来了,线程2就进来了。
      s = new Student();
      }
      return s;
      }
      }  

    • 懒汉式(双重同步锁)
      class Student
      {
      private Student(){}
      
      private static final Student s = null;
      
      public static Student getInstance(){
      
          synchronized(Student.class){
         if(s==null) 
         {
           //线程1就进来了,线程2就进来了。
          s = new Student();
          }
      
        }
      return s;
      }
      }  
      

        

  5. 常见应用场景
    • 项目中用于读取配置文件的类。

    • 数据库连接池。因为数据库连接池是一种数据库资源。

    • Spring中,每个Bean默认都是单例的,这样便于Spring容器进行管理。

 

posted @ 2020-07-11 14:33  小呆俊  阅读(120)  评论(0编辑  收藏  举报
/*标题彩虹滚动字*/ #blogTitle h1 a{ background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2), color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) ); color: transparent;-webkit-text-fill-color: transparent; -webkit-background-clip: text; -webkit-background-size: 200% 100%; -webkit-animation: maskedAnimation 2s infinite linear; -webkit-background-clip: text;-moz-background-clip: text;-ms-background-clip: text /*文字颜色变化*/ @keyframes maskedAnimation { 0% { background-position: 0 0; } 100% { background-pos