zoukankan      html  css  js  c++  java
  • 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容器进行管理。

  • 相关阅读:
    POJ 1703 Find them, Catch them
    POJ 2236 Wireless Network
    POJ 2010 Moo University
    POJ 2184 Cow Exhibition
    POJ 3280 Cheapest Palindrome
    POJ 3009 Curling 2.0
    POJ 3669 Meteor Shower
    POJ 2718 Smallest Difference
    POJ 3187 Backward Digit Sums
    POJ 3050 Hopscotch
  • 原文地址:https://www.cnblogs.com/lj1507899927/p/13283506.html
Copyright © 2011-2022 走看看