单例设计(懒汉式和饿汉式)

单例设计

概念:
单例设计模式:在内存中,只存在该类的一个对象

懒汉式

代码:

public class Student {
    private static Student student=null;    //进行私有构造

    private Student() {
    }

    public synchronized static Student getStudent(){    //给外界提供一个公共的静态方法,返回改类的一个对象加上synchronized锁 避免多线程环境下,有可能出现new了多次
        if(student==null){
            student=new Student();
        }
       return student;
    }
}

public class MyTest {
    public static void main(String[] args) {
        Student student = Student.getStudent();
        Student student1 = Student.getStudent();
        System.out.println(student==student1);//输出为true所以是地址相同对象
    }
}

懒汉式:晚创建对象,特点是延迟加载。当我们用的时候它才会去建立对象。(在多线程中的时候可能会出现线程安全问题)
特点:线程安全,调用效率不高,可以延时加载。

饿汉式

代码:

public class Teacher {
    private static Teacher teacher=new Teacher();//开始直接创建对象
    private Teacher() {
    }

    public static Teacher getTeacher(){

        return teacher;
    }

}

public class MyTest2 {
    public static void main(String[] args) {
        Teacher teacher = Teacher.getTeacher();
        Teacher teacher1 = Teacher.getTeacher();
        System.out.println(teacher==teacher1);//输出为true所以为地址相同对象
    }
}

饿汉式:写类的时候直接就创建对象。

特点:线程安全,调用率高,但是,不能延迟加载。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值