单例设计模
(1)保证类在内存中只有一个对象。
(2)怎么保证:
A:构造私有
B:自己造一个对象
C:提供公共访问方式
(3)两种方式:
A:懒汉式(面试)
public class Student {
private Student(){}
private static Student s = null;
public synchronized static Student getStudent() {
if(s == null) {
s = new Student();
}
return s;
}
}
B:饿汉式(开发)
public class Student {
private Student(){}
private static Student s = new Student();
public static Student getStudent() {
return s;
}
}
|
|