单例模式有两种:一种是:饿汉式 一种是:懒汉式
饿汉式如下:
class Person {
//1.私有化构造器
private Person(){
}
//2.私有化对象
private static Person instance = new Person();
//3.提供给外部访问的方法
public static Person getInstance(){
return instance;
}
}
懒汉式:可能存在线程安全问题,一般情况下,不建议使用
class Zoo {
private Zoo(){
}
private static Zoo instance = null;
public static Zoo getInstance(){
if(instance == null){
instance = new Zoo();
}
return instance;
}
}