// 饿汉式 : 一上来就创建对象,吃掉内存
class Student {
private Student(){}
private Student stu = new Student();
public static Student getInstance(){
return stu;
}
}
// 懒汉式
class Student {
private Student(){}
private Student stu;
public static Student getInstance(){
if(stu==null){
stu = new Studnet();
}
return stu;
}
}
//懒汉式:多线程环境
class Student {
private Student(){}
private Student stu;
public static Student getInstance(){
if(stu==null){
synchronized(Student.class){
if(stu==null){
stu = new Studnet();
}
}
}
return stu;
}
} |
|