public class Elvis {
//第一种静态成员是一个final域 public static final Elvis INSTANCE = new Elvis(); //第二种公有成员是一个静态工厂方法 private static final Elvis INSTANCE2 = new Elvis(); public static Elvis getInstance() { return INSTANCE2; } public static void main(String[] args) { // TODO Auto-generated method stub}
}
///
public enum Elvis {
INSTANCE; private Elvis(){ System.out.println("构造器"); } public void print(int i) { System.out.println("number: " + i); } public static void main(String[] args) { // TODO Auto-generated method stub Elvis e1 = Elvis.INSTANCE; Elvis e2 = Elvis.INSTANCE; Elvis e3 = Elvis.INSTANCE; e1.print(1); e2.print(2); e3.print(3); }}
单元素的枚举类型已经成为实现Singleton的最佳方法