Java – singleton mode
Like my previous question, this question refers to effective Java I have many sub - questions this time
>Privileged clients can use accessibleobject The setaccessible () method calls the private constructor reflexively If you need to guard against this operation, modify the constructor How exactly do I call a private constructor? What is accessibleobject setAccessible()? > What is your expert's approach to singles?
// Approach A public class Test{ public static final Test TestInstance = new test(); private test(){ ... } . . . } // Approach B public class Test{ private static final Test TestInstance = new test(); private test(){ ... } public static Test getInstance() { return TestInstance; } . . . }
Is the second method more flexible in case we have to check a new instance every time or check the same instance every time? > What if I try to clone a class / object? > Single element enumeration types are the best way to implement singletons Why? What about?
Solution
Obviously, the class itself can call private constructors (for example, from static factory methods) Conversely, Bloch is talking about:
import java.lang.reflect.Constructor; public class PrivateInvoker { public static void main(String[] args) throws Exception{ //compile error // Private p = new Private(); //works fine Constructor<?> con = Private.class.getDeclaredConstructors()[0]; con.setAccessible(true); Private p = (Private) con.newInstance(); } } class Private { private Private() { System.out.println("Hello!"); } }
Usually, the first one is popular The second (assuming you test whether the testinstance is null before returning a new instance) obtains delayed loading at the expense of synchronization or thread insecurity
When your second example does not assign an instance to testinstance when declared, I wrote the above content As mentioned above, the above considerations are irrelevant
This is not about flexibility, but about when it costs to create a (and unique) instance If you choose a) it is generated when the class is loaded This is usually good because classes are loaded only when needed
When your second example does not assign an instance to testinstance when declared, I wrote the above content As mentioned earlier, in both cases, singleton will be created when the class is loaded
Singles should not be allowed to clone for obvious reasons Clonenotsupportedexception should be thrown. It will be thrown automatically unless clonable is implemented for some reason
Examples of this are in the book, just like the reasons What part don't you understand?