zoukankan      html  css  js  c++  java
  • Singleton: 单例模式!

     Singleton: 单例模式!

     
     01.在整个应用程序中,一个类只有一个实例对象!
     02.这个实例对象只能通过本类中创建! ====》私有化构造!!
     03.别人还得使用,通过本类中创建的一个对外访问的接口,来返回本类的实例对象!
     
     
     
     创建单例模式的步骤:
     1.创建静态变量
     2.私有化构造
     3.提供对外访问的接口
     
     
     实现单例模式的3种方式:
     1.懒汉式
     2.饿汉式          推荐使用
     3.双重校验锁

    /**
     * 懒汉式
     * 之后用户第一次 调用getInstance()的时候,对象的唯一实例才会被创建!
     */
    public class Student {

     // 1.创建静态变量
     private static Student stu;

     // 2.私有化构造
     private Student() {
     }

     // 3.提供对外访问的接口
     public static synchronized Student getInstance() {
      if (stu == null) {
       stu = new Student(); // 唯一的对象实例
      }
      return stu;
     }

    }

    /**
     * 饿汉式
     *  在类装载的时候,单例对象就被创建了!
     */
    public class Student2 {

     // 1.创建静态变量
     private static Student2 stu = new Student2();

     // 2.私有化构造
     private Student2() {
     }

     // 3.提供对外访问的接口
     public static synchronized Student2 getInstance() {
      return stu;
     }

    }

    /**
     * 双重校验锁
     *     为了保证多线程情况下,单例的正确性!
     */
    public class Student3 {

     // 1.创建静态变量
     private static Student3 stu;

     // 2.私有化构造
     private Student3() {
     }

     // 3.提供对外访问的接口
     public static synchronized Student3 getInstance() {
      if (stu == null) {
       synchronized (Student3.class) {
        if (stu == null) {
         stu = new Student3();
        }
       }
      }
      return stu;
     }

    }

    演示类

    public class StudentDemo {

     public static void main(String[] args) {
      // 实例化对象
      Student3 stu1 = Student3.getInstance();
      Student3 stu2 = Student3.getInstance();
      System.out.println(stu1 == stu2);
     }
    }

  • 相关阅读:
    20200414:mysql原子性和持久性怎么保证
    20200417:说说redis的rdb原理。假设服务器的内存8g,redis父进程占用了6g,子进程fork父进程后,子父进程总共占用内存12g,如何解决内存不足的问题?(挖)
    [九省联考2018]秘密袭击coat
    CF1158F Density of subarrays
    忘情
    [IOI2018] meetings 会议
    [AGC013E] Placing Squares
    [八省联考2018]林克卡特树
    [NOI2016] 国王饮水记
    [十二省联考 2019]皮配
  • 原文地址:https://www.cnblogs.com/WillimTUrner/p/8289682.html
Copyright © 2011-2022 走看看