单例设计模式(饿汉式,懒汉式(1,有线程安全问题,2,安全高效))

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wdx_1136346879/article/details/85642582

package cn.itcast.mobilesafexian2.test;

public class Student {
/* (1)单例模式(只需创建一个对象) (外界访问直接Student.getStudent 即可获得对象 )

  • (饿汉式:在加载的时候创建对象{有可能整个项目运行下来没有用这个对象,
    而用户没有用但是却创建了}){无线程安全问题,应为只有返回}
    保证类在内存中只有一个对象。
    (2)如何保证呢?
    在本类中
    A:构造私有(不让在外接创建(new))
    B:本身提供一个对象(为了保证只有一个对象)
    C:对外提供公共的访问方式(加static)
    //保证内在
    private Student(){};//构造私有(不让外界创造对象)
    //为了不让外界访问(直接赋值)加 private
    private static Student s = new Student();
    public static Student GetStudent(){//C:对外提供公共的访问方式(为了外界直接访问加static)
    return s;
    }*/

    //2 单例模式 (懒汉式:在使用的时候创建){有线程安全问题:因为需要(共享数据s和多步骤)判断,造对象,返回}
    //懒汉式用了一种思想 :延时加载(用的时候再去创建)
    //这种方法安全了 但影响效率
    /* private Student(){};
    private static Student s = null;
    public synchronized static Student GetStudent(){//不安全 加锁但浪费性能
    1,s= new Student();//存在问题每次调用都要 创建对象{所以加个判断 if(snull)}*
    //s1,s2,s3
    if(s
    null){
    //s1,s2,s3
    s=new Student();
    }

     return s;
    

    }*/
    //懒汉式(安全高效模式)
    private Student(){};
    private static Student s = null;
    public static Student GetStudent(){//不安全 加锁
    /1,s= new Student();//存在问题每次调用都要 创建对象{所以加个判断 if(s==null)}
    */
    if(snull){
    // A, B
    //只有第一次进来时有锁子
    synchronized (Student.class) {
    //当ab 都进进来时
    if(s
    null){
    s=new Student();
    }
    }
    }
    return s;
    }

}

猜你喜欢

转载自blog.csdn.net/wdx_1136346879/article/details/85642582