直接上代码:
1 public enum Boss { 2 3 INSTANCE; 4 5 private String name; 6 7 public void doSomeThing() { 8 System.out.println(name + " is doing something now..."); 9 } 10 11 public String getName() { 12 return name; 13 } 14 15 public void setName(String name) { 16 this.name = name; 17 } 18 19 }
注:java中的enum是一个彻彻底底的class,可以自由添加其它属性、方法,所以完全可以当成一个class来用。
验证:
1 @Test 2 public void testSingleton() { 3 4 Boss b1 = Boss.INSTANCE; 5 b1.setName("张三"); 6 b1.doSomeThing();//张三 is doing something now... 7 8 Boss b2 = Boss.INSTANCE; 9 b2.doSomeThing();//张三 is doing something now... 10 11 System.out.println(b1.equals(b2));//true 12 13 }
11行输出的true,已经证明了b1与b2是同一个对象,而且这种方式绝对防止反射调用私有构造器来破坏单例。
时间: 2024-09-20 00:27:13