Java语言-64:单例模式之饿汉式和懒汉式

1、概述:单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。单例模式就是为了避免不一致状态,避免政出多头

 单例模式有以下特点:

  1)、单例类只能有一个实例。
  2)、单例类必须自己自己创建自己的唯一实例。

  3)、单例类必须给所有其他对象提供这一实例

2、单例模式常用的分为饿汉式和懒汉式

        1)饿汉式在加载那个类的时候,对象的创建工作就已经完成了!

                思路:A、构造方法私有化(这样类就不能被实例化)

                      B、实例化单例对象,对象为静态的(这样就只会实例化一次),私有的(安全,外部不能直接Singleton.instance调用)

                   C、提供一个静态方法(静态方法,类可以直接调用),获取单例

        2)代码举例:         

 package Singleton_hungry_model;
//饿汉式
public class Student {
// 无参构造私有化,目的为了防止用户创建对象的时候,会产生多个对象!(不让用户通过构造方法创建对象)
// 为了不让直接通过无参构造方法创建该类对象
private Student() {


}


// 成员位置创建该类的实例
// 静态方法只能访问静态变量
// 加入私有修饰
private static Student s = new Student();


// 提供一个公共的成员方法
public static Student getStudent() {
return s;


}

}

package Singleton_hungry_model;
public class StudentTest {
public static void main(String[] args) {
//创建学生对象
Student s1 = Student.getStudent();
Student s2 = Student.getStudent();
System.out.println(s1 == s2);
System.out.println(s1);
System.out.println(s2);

}

}

            3)懒汉式:懒汉式和饿汉式在设计上基本一样

            类加载的时候只是声明一下,调用这个单例的时候才实例化(比较懒,不主动去实例对象)
                A、先声明一个单例,并不实例化单例对象
                B、在get方法里面去判断,如果没有实例这个对象,就将单例对象实例化再返回
                对比:
            懒汉模式:类加载快,获取对象慢,线程安全的
            饿汉模式:类加载慢,获取对象快,线程不安全

            总结:static修饰的变量、方法数据类,可以通过类直接调用

                    设计思路:A、私有化构造对象

                              B、申明单例对象

                              C、提供静态方法,获取单例

            4)代码举例:

package Singleton_lazy_model;
//懒汉式:
public class Teacher {
//私有化构造对象
private Teacher() {

}
//申明单例对象
private static Teacher t = null;

//提供公共的同步静态成员方法
public synchronized static Teacher getTeacher() {
// public static Teacher getTeacher() {
if(t == null) {
t = new Teacher();
}
return t;

}

}

package Singleton_lazy_model;


public class TeacherTest {


public static void main(String[] args) {
// 动用getTeacher方法
Teacher t1 = Teacher.getTeacher();
Teacher t2 = Teacher.getTeacher();
System.out.println(t1 == t2);// true
System.out.println(t1);// Singleton_lazy_model.Teacher@70dea4e
System.out.println(t2);// Singleton_lazy_model.Teacher@70dea4e


}


}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值