单例模式:只创建一个对象实例
单例模式的实现方式有饿汉式与懒汉式
饿汉式:从一开就创建对象
public class Hunger {
private static Hunger hunger=new Hunger();
private Hunger(){}
public static Hunger newInstance(){
return hunger;
}
}
懒汉式:只有使用时才创建
class Student{
private static Student s;
private Student(){}
public static synchronized Student newInstance(){
if (s==null){
s=new Student();
}
return s;
}
}
**懒汉式:**双重检查
class A{
private A(){}
private static volatile A a;
public static A newInstance(){
if (a==null){
synchronized (A.class){
if (a==null){
a=new A();
}
}
}
return a;
}
}