java单例模式
(1),懒汉式单例
优点: 第一次调用才初始化,避免浪费内存.
缺点: 必须加synchronized才能保证单例,但加锁会影响效率.
public class Student{
private static Student student;
private Student(){}
public static synchronized Student getInstance(){
if(student=null){
student=new Student();
}
return student;
}
}
(2),饿汉式单例
优点: 没有加锁,执行效率会提高.
缺点: 类加载时就初始化,浪费内存.
public class Student{
public static final Student stu=new Student();
private Student(){}
public static Student getInstance(){
return stu;
}
}
(3),登记式单例
内部类只有在外部类被调用才加载;又不用加锁,此模式有上述两种模式的优点,屏蔽了它们的缺点,才是最好的单例模式.
public class Student{
private Student(){}
public static Student createObj(){
return Holder.stu;
}
private static class Holder{
private static final Student stu=new Student();
}
}