zoukankan      html  css  js  c++  java
  • Java 单例设计模式

    Singleton:单例模式

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

    2.这个实例对象只能通过本类中创建=====>私有化构造

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

    实现单例的3种模式:

    1.懒汉式:只有用户第一次调用getInstence()的时候,对象的唯一实例才会被调用

    创建懒汉单例模式的步骤:

    01.创建静态变量

    private static Student stu;

    02.私有化构造

    private Student(){}

    03.提供对外访问的接口

    public static synchronized Student getInstence(){

    if(stu==null){

    stu=new Student();

    }

    return stu;

    }

    04.测试类中使用

    Student.getInstence()

    2.饿汉式:(推荐使用)在类加载的时候,单例对象就被创建,是线程安全的

    创建饿汉单例模式的步骤:

    01.创建静态变量

    private static Student stu=new Student();

    02.私有化构造

    private Student(){}

    03.提供对外访问的接口

    public static synchronized Student getInstence(){

    return stu;

    }

    04.测试类中使用

    Student.getInstence()

    3.双重校验锁:为了保证多线程情况下,单例的正确性

    创建双重校验锁单例模式的步骤:

    01.创建静态变量

    private static Student stu;

    02.私有化构造

    private Student(){}

    03.提供对外访问的接口

    public static synchronized Student getInstence(){

    if(stu==null){

    synchronized(Student.class){

    if(stu==null){

    stu=new Student();

    }

    }

    }

    return stu;

    }

    04.测试类中使用

    Student.getInstence()

     

  • 相关阅读:
    Ubuntu安装gfortran
    Ubuntu12.04安装vscode i386
    PowerShell让系统可以执行.ps1文件
    Gitlab. Disable user creation on welcome page
    开源项目和工具列表
    布隆过滤器 (Bloom Filter)
    信息系统综合知识概览
    Hadoop实战之四~hadoop作业调度详解(2)
    Hadoop实战之三~ Hello World
    Hadoop实战之二~ hadoop作业调度详解(1)
  • 原文地址:https://www.cnblogs.com/s10-/p/8287252.html
Copyright © 2011-2022 走看看