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()

     

  • 相关阅读:
    UVALive 7141 BombX
    CodeForces 722D Generating Sets
    CodeForces 722C Destroying Array
    CodeForces 721D Maxim and Array
    CodeForces 721C Journey
    CodeForces 415D Mashmokh and ACM
    CodeForces 718C Sasha and Array
    CodeForces 635C XOR Equation
    CodeForces 631D Messenger
    田忌赛马问题
  • 原文地址:https://www.cnblogs.com/s10-/p/8287252.html
Copyright © 2011-2022 走看看