单例模式:私有静态成员变量+私有构造方法+公有静态方法
饿汉式:当类被加载时就创建了该类的实例
public class BeanFactory {
private static BeanFactory beanFactory = new BeanFactory();
private BeanFactory(){
System.out.println("饿汉式");
}
public static BeanFactory getInstance(){
return beanFactory;
}
}
懒汉式:当用到该类时才会创建该类的实例
public class BeanFactory2 {
private static BeanFactory2 beanFactory = null;
private BeanFactory2(){
System.out.println("懒汉式");
}
public static BeanFactory2 getInstance(){
if(beanFactory == null){
beanFactory = new BeanFactory2();
}
return beanFactory;
}
}