单例模式:保证类的内存只有一个对象,通过私有构造方法,自己创建对象,提供公共访问方法实现。
分两种:
饿汉式:类一加载就创建对象
懒汉式:用的时候,创建对象
面试的时候考懒汉式:因为可能会出现线程安全问题,所以记得用同步“synchronize”
开发的时候用饿汉式:因为它是不会出现问题的单例模式public class Student {
private Student() {
};
private static Student s = null;
public synchronized static Student getStudent() {
if (s==null) {
s =new Student();
}
return s;
}
} public class StudentDemo {
public static void main(String[] args) {
Student s1 = Student.getStudent();
Student s2 = Student.getStudent();
System.out.println(s1==s2);
}
|
|