java单例模式 的饿汉式和懒汉式代码实现
程序员文章站
2024-03-14 20:07:47
...
package day10_9;
// 单例模式 饿汉式
public class Singleton {
public static void main(String[] args) {
Student s1 = Student.getStudent();
Student s2 = Student.getStudent();
System.out.println(s1 == s2);
Teacher t1 = Teacher.getTeacher();
Teacher t2 = Teacher.getTeacher();
System.out.println(t1 == t2);
}
}
// 饿汉式
class Student {
private Student() {
}
private static Student student = new Student();
public static Student getStudent() {
return student;
}
}
// 懒汉式
class Teacher {
private Teacher() {
}
private static Teacher teacher = null;
public static Teacher getTeacher() {
if (teacher == null) {
teacher = new Teacher();
}
return teacher;
}
}
上一篇: CentOS 7 安装 JDK 1.8
下一篇: JDK 安装配置