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

    单例模式:

    01.在整个应用程序中,一个类只有一个实例对象!

    02.这个实例对象只能通过本类中创建!====》私有构造方法

    03.别人还得使用,通过本类中创建的一个对外访问的接口,来返回本类的实例对象!

    创建单例模式的步骤:

    1.创建静态变量

    2.私有构造

    3.提供对外访问接口

    实现单例模式的3种方式:

    1.懒汉式:

     用户第一次 调用getInstance()的时候,对象的唯一视力才会被创建

     特点:加载类是比较快,但运行时获取对象速度慢,线程不安全

    package com.xdf.bean;
    
    /**
     * 懒汉式:
     * 之后用户第一次 调用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;
        }
    
    }

    2.饿汉式   (推荐使用):

    在类装载时候,单例对象就被创建了

    特点:加载类是比较慢,但运行时获取对象的速度快,线程安全

    package com.xdf.bean;
    
    /**
     * 饿汉式:
     * 在类装载的时候,单例对象就被创建了!
     */
    public class Student2 {
    
        // 1.创建静态变量
        private static Student2 stu = new Student2();
    
        // 2.私有化构造
        private Student2() {
        }
    
        // 3.提供对外访问的接口
        public static synchronized Student2 getInstance() {
            return stu;
        }
    
    }

    3.双重校验法:

    package com.xdf.bean;
    
    /**
     * 双重校验锁:
     * 为了保证多线程情况下,单例的正确性!
     */
    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;
        }
    
    }
  • 相关阅读:
    jQuery中$.get、$.post、$.getJSON和$.ajax的用法
    easyui笔记
    查询用户表中都存在那些表
    在tomcat下端口号设置后面 添加 URIEncoding=UTF-8可以使传递中文的不乱码
    jquery 实现ajax 上传文件的功能(使用插件 ajaxfileupload)
    oracle 分页(rownum的理解) 以及 树节点的查询
    Server.Transfer,Response.Redirect用法点睛
    Excel 生成sql语句
    exjs3.2的gridPanel的表头总宽度与列的总宽度不一致的解决方案
    Nopi .net下面的Excel第三方dll
  • 原文地址:https://www.cnblogs.com/liutianci/p/8287335.html
Copyright © 2011-2022 走看看