java Singleton 实现单例的三种方式
ElvisPublic
public class ElvisPublic {
public static final ElvisPublic INSTANCE = new ElvisPublic();
private ElvisPublic() {
}
}
ElvisPrivate
public class ElvisPrivate {
private static final ElvisPrivate INSTANCE = new ElvisPrivate();
private ElvisPrivate() {
}
public static ElvisPrivate getInstance() {
return INSTANCE;
}
private Object readResolve() {
return INSTANCE;
}
}
ElvisEnum
class Resource{
public void hello() {
System.out.println("hello");
}
}
public enum ElvisEnum{
INSTANCE;
private Resource instance;
ElvisEnum() {
instance = new Resource();
}
public Resource getInstance() {
return instance;
}
}
class ElvisMain {
public static void main(String[] args) {
Resource info = ElvisEnum.INSTANCE.getInstance();
info.hello();
}
}