直接上代码:
public enum Boss { INSTANCE; private String name; public void doSomeThing() {
System.out.println(name + " is doing something now...");
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} }
注:java中的enum是一个彻彻底底的class,可以*添加其它属性、方法,所以完全可以当成一个class来用。
验证:
@Test
public void testSingleton() { Boss b1 = Boss.INSTANCE;
b1.setName("张三");
b1.doSomeThing();//张三 is doing something now... Boss b2 = Boss.INSTANCE;
b2.doSomeThing();//张三 is doing something now... System.out.println(b1.equals(b2));//true }
11行输出的true,已经证明了b1与b2是同一个对象,而且这种方式绝对防止反射调用私有构造器来破坏单例。