单例模式:(饿汉式):
package h.l.pattern3;
public class Student {
private Student() {
}
private static Student s = new Student();
public static Student getStudent() {
return s;
}
}
package h.l.pattern3;
public class StudentDemo {
public static void main(String[] args) {
Student s1 = Student.getStudent();
Student s2 = Student.getStudent();
System.out.println(s1 == s2);
}
}
所谓饿汉式就是一加载类就创建一个对象,就好比,你放学回家很饿,一看见桌上的馒头就吃了一样的道理。
单例模式:(懒汉式):
package h.l.pattern3;
public class Student {
private Student() {
}
private static Student s = null;
public static Student getStudent() {
if (s == null) {
s = new Student();
}
return s;
}
}
package h.l.pattern3;
public class StudentDemo {
public static void main(String[] args) {
Student s1 = Student.getStudent();
Student s2 = Student.getStudent();
System.out.println(s1 == s2);
}
}
所谓懒汉式就是用的时候才new对象。
总结:单例模式的思想就是:保证类在内存中只有一个思想。如果写单例模式,那么开发中建议使用饿汉式,面试中建议懒汉式
开发中:饿汉式(是不会出现问题的单例模式)
面试中:懒汉式(可能会出现问题的单例模式)
A:懒加载(延迟加载)
B:线程安全问题:
a:是否是多线程 是
b:是否有共享数据 是
c:是否有多条语句操作共享数据 是
因此在懒加载中要保证线程安全,则需要在方法上加上sychronized关键字,保证一个方法是原子操作。JDK源码中runtime类(作用是使应用程序能够与其运行的环境想连接)也是饿汉式的体现。
注:以上文章仅是个人学习过程总结,若有不当之处,望不吝赐教。