欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java单例模式 的饿汉式和懒汉式代码实现

程序员文章站 2024-03-14 20:07:47
...

java单例模式 的饿汉式和懒汉式代码实现

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;

	}

}