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);
     }
    }

  • 相关阅读:
    ubuntu 14.04搭建PHP项目基本流程
    linux下 lvm 磁盘扩容
    LVM基本介绍与常用命令
    Linux LVM逻辑卷配置过程详解
    mysql 5.7中的用户权限分配相关解读!
    linux系统维护时的一些小技巧,包括系统挂载新磁盘的方法!可收藏!
    linux系统内存爆满的解决办法!~
    源、更新源时容易出现的问题解决方法
    NV显卡Ubuntu14.04更新软件导致登录死循环,不过可以进入tty模式
    一些要注意的地方
  • 原文地址:https://www.cnblogs.com/WillimTUrner/p/8289682.html
Copyright © 2011-2022 走看看