1,饿汉式
public class Student {
// 构造私有
private Student() {
}
// 自己造一个
// 静态方法只能访问静态成员变量,加静态
// 为了不让外界直接访问修改这个值,加private
private static Student s = new Student();
// 提供公共的访问方式
// 为了保证外界能够直接使用该方法,加静态
public static Student getStudent() {
return s;
}
}
/*
* 单例模式:保证类在内存中只有一个对象。
*
* 如何保证类在内存中只有一个对象呢?
* A:把构造方法私有
* B:在成员位置自己创建一个对象
* C:通过一个公共的方法提供访问
*/
public class StudentDemo {
public static void main(String[] args) {
// Student s1 = new Student();
// Student s2 = new Student();
// System.out.println(s1 == s2); // false
// 通过单例如何得到对象呢?
// Student.s = null;
Student s1 = Student.getStudent();
Student s2 = Student.getStudent();
System.out.println(s1 == s2);
System.out.println(s1); // null,cn.itcast_03.Student@175078b
System.out.println(s2);// null,cn.itcast_03.Student@175078b
}
}
2,饿汉式
/*
* 单例模式:
* 饿汉式:类一加载就创建对象
* 懒汉式:用的时候,才去创建对象
*
* 面试题:单例模式的思想是什么?请写一个代码体现。
*
* 开发:饿汉式(是不会出问题的单例模式)
* 面试:懒汉式(可能会出问题的单例模式)
* A:懒加载(延迟加载)
* B:线程安全问题
* a:是否多线程环境 是
* b:是否有共享数据 是
* c:是否有多条语句操作共享数据 是
*/
public class Teacher {
private Teacher() {
}
private static Teacher t = null;
public synchronized static Teacher getTeacher() {
// t1,t2,t3
if (t == null) {
//t1,t2,t3
t = new Teacher();
}
return t;
}
}
public class TeacherDemo {
public static void main(String[] args) {
Teacher t1 = Teacher.getTeacher();
Teacher t2 = Teacher.getTeacher();
System.out.println(t1 == t2);
System.out.println(t1); // cn.itcast_03.Teacher@175078b
System.out.println(t2);// cn.itcast_03.Teacher@175078b
}
}