3rd: Hardening the Singleton property with a private constructor or enumeration type
This, in general, is a small trick that declares a constructor as private and can be implemented in a single case. There are several ways to achieve this.
① the most traditional single-instance implementation pattern, there may be many variants, the core idea is the privatization of the constructor.
public class Singleton { static final Singleton INSTANCE = new Singleton (); private Singleton () {}; public static Singleton getinstance () { return Instan CE; public static void main (string[] args) {singleton.getinstance (); }}
② is implemented with enumeration types, is more concise, provides a serialization mechanism for free, and can absolutely prevent multiple instantiations (methods ① If multiple instances can still be generated using serialization), even in the face of complex serialization or reflection attacks. Although this approach is not widely used, single-element enumeration types have become the best way to implement Singleton .
Public enum Singleton { INSTANCE; Private String s; Public String GetS () { return s; } Public void sets (String s) { this. s = s; } }
In fact, enum anti-compilation is still essentially a class, it can also have its own properties and methods.
4th: The ability to harden non-instancing with private constructors
This is actually a little trick. For example, we often write the tool class, the tool class does not want to be instantiated, the instantiation does not have any meaning to it.
The first solution is to make the tool class an abstract class , but this is still not possible because the subclass can still be instantiated after it inherits.
Therefore, when a class does not need to be inherited and does not need to be instantiated, this effect can be achieved as long as the constructor for this class is privatized.
Public classUtil {//privatization of constructors, forcing cannot instantiate PrivateUtil () {}; Public StaticString getstrofobject (Object o) {//The method of converting an object to string, slightly return""; } Public StaticString PARSEDATETOYYYYMMDD (Date d) {//The method of converting date to this format in 2016-03-05 is slightly return""; }}
Effective JAVA2 reading notes-Creating and destroying objects (ii)