单例模式是天然的同步锁对象,这个类只会产生一个实例(一个对象)
//饿汉式单例
public class A {
private A() {
} // 1私有化构造方法---别人不能new A()
private static A a = new A();
public static A getA() { // 2提供公开静态的get方法
return a;
}
}
//懒汉式单例
public class A {
private A(){
}
private static A a = null;
public static A getA(){
If(a==null){
a=new A();
}
return a;
}
}
两者区别:饿汉随着类的加载而完成单例的初始化;懒汉当调用getA时才会初始化单例