?????м????Ч??????????????????????????????????κ???????????????????????
????????????????????????????Σ????????????????Χ????????????????????????????????????????????????????????????????????????????????????????????????????????????д???????????????????????????????????????е???????????????
???????????????????о??????????????????????????????Ч?????????????????????????????κ?????????????????????????????????????????????
????Final???
?????????????????????л???????????????е?static final????
????public class FooSingleton {
????public final static FooSingleton INSTANCE = new FooSingleton();
????private FooSingleton() { }
????public void bar() { }
????}
????????????static????????????????е???????????????????ε??á??????????????ж????????????JVM????????????????????????????????????????÷????setAccessible(true)??????????????????μ??????
????Constructor[] constructors = FooSingleton.class.getDeclaredConstructors();
????Constructor constructor = constructors[0];
????constructor.setAccessible(true);
????FooSingleton spuriousFoo = (FooSingleton) constructor.newInstance(new Object[0]);
?????????????????????????????ε???????統(tǒng)??????ε??????????????????????FooSingleton???????????????????????
????public class FooSingleton2 {
????private static boolean INSTANCE_CREATED;
????public final static FooSingleton2 INSTANCE = new FooSingleton2();
????private FooSingleton2() {
????if (INSTANCE_CREATED) {
????throw new IllegalStateException("You must only create one instance of this class");
????} else {
????INSTANCE_CREATED = true;
????}
????}
????public void bar() { }
????}
??????????????????Щ??????????????μ??????????????????????????INSTANCE_CREATED??Σ???????????????????
????Field f = FooSingleton2.class.getDeclaredField("INSTANCE_CREATED");
????f.setAccessible(true);
????f.set(null?? false);
????Constructor[] constructors = FooSingleton2.class.getDeclaredConstructors();
????Constructor constructor = constructors[0];
????constructor.setAccessible(true);
????FooSingleton2 spuriousFoo = (FooSingleton2) constructor.newInstance(new Object[0]);
?????????????κη?????????????????????????????????С?
???????????
???????????????????е???????????????
????public class FooSingleton3 {
????public final static FooSingleton3 INSTANCE = new FooSingleton3();
????private FooSingleton3() { }
????public static FooSingleton3 getInstance() { return INSTANCE; }
????public void bar() { }
????}
????getInstance()?????????????????????????á????????????????????????????????????Щ??????磬??????????API??????£????????????getInstance()????????????е????????У???????????????????????????