单例模式分为(懒汉式,饿汉式)
懒汉式(对象的延迟加载)
Public class Student{
Private Student(){}
Private static Student stu=null;
Public static Student getInstance(){
If(stu!=null)
Stu=new Student();
else
Return stu;
}
}
饿汉式
Public class Student{
Private Student(){}
Private static Student stu=new Student();
Public static Student getInstance(){
Return stu;
}
}
一般开发的时候都是采用饿汉式,因为懒汉式存在着隐患要想解决就用双重判断+同步线程就行了代码如下:
Public class Student{
Private Student(){}
Private static Student stu=null;
Public static Student getInstance(){
If(stu==null)
{
Synchronized(Student.class)
{
If(stu==null)
Stu=new Student();
}
}
Return stu;
}
代码能看懂,不知道单例模式一般都用在什么时候,求深刻理解???? |