单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式
特点:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其他对象提供这一实例
懒汉式:
代码语言:javascript复制package com.example;
/**
* 懒汉式
* 加锁 synchronized线程安全
*/
public class Student {
private static Student student;
private Student(){};
public static synchronized Student getInstance(){
if (student == null) {
student = new Student();
}
return student;
}
public static void main(String[] args) {
Student student1 = Student.getInstance();
Student student2 = Student.getInstance();
if(student1 == student2){
System.out.println("同一个学生");
}else{
System.out.println("不是同一个学生");
}
}
}
输出结果:
饿汉式:
代码语言:javascript复制package com.example;
/**
* 饿汉式
* 多线程安全
* 类加载时就初始化
*/
public class Student1 {
private static Student1 student1 = new Student1();
private Student1(){};
public static synchronized Student1 getInstance(){
return student1;
}
public static void main(String[] args) {
Student1 student1 = Student1.getInstance();
Student1 student2 = Student1.getInstance();
if(student1 == student2){
System.out.println("同一个学生");
}else{
System.out.println("不是同一个学生");
}
}
}
输出结果:
双重校验锁
代码语言:javascript复制package com.example;
/**
* 双重校验锁
* 线程安全
*/
public class Student2 {
private volatile static Student2 student2;
private Student2 (){}
public static Student2 getInstance() {
if (student2 == null) {
synchronized (Student2.class) {
if (student2 == null) {
student2 = new Student2();
}
}
}
return student2;
}
public static void main(String[] args) {
Student2 student1 = Student2.getInstance();
Student2 student2 = Student2.getInstance();
if(student1 == student2){
System.out.println("同一个学生");
}else{
System.out.println("不是同一个学生");
}
}
}
输出结果: