单例设计模式——恶汉式与懒汉式
- 恶汉式:立即加载,实例在创建之前就已经加载
- 懒汉式:延迟加载,实例在访问时才需要加载
单例设计模式需要注意的问题
- synchronized(this)方法行不行?不行
- getInstance()方法直接锁效率高不高?不高
- 面试中常用哪一个? 懒汉式
代码实现
1、恶汉式
class Student1{
private Student1() {
}
private static Student1 stu = new Student1();
public static Student1 getStudent() {
return stu;
}
}
2、懒汉式(synchronized锁getInstance方法)
class Student2{
private Student2() {
}
private static Student2 stu = null;
public synchronized static Student2 getStudent() {
if(stu == null)
stu = new Student2();
return stu;
}
}
3、懒汉式(双重锁)
class Student3{
private Student3() {
}
private static Student3 stu = null;
public static Student3 getStudent() {
if(stu == null) {
synchronized(Student3.class) {
if(stu == null) {
stu = new Student3();
}
}
}
return stu;
}
}
4、测试
public class StudentMain {
public static void main(String[] args) {
Student1 stu1 = Student1.getStudent();
Student1 stu2 = Student1.getStudent();
System.out.println(stu1==stu2);
Student2 stu3 = Student2.getStudent();
Student2 stu4 = Student2.getStudent();
System.out.println(stu3==stu4);
Student3 stu5 = Student3.getStudent();
Student3 stu6 = Student3.getStudent();
System.out.println(stu5==stu6);
}
}