Singleton reflection, and the vulnerability of sequences solution!

Using the reflection technique to obtain a different example, the following is a simple formula of starving singleton pattern code implements:

When we need to get the Singleton object when directly call the static method getInstance on it:

But learned reflection of people know that technology can also be obtained through reflection to an instance of a class of objects, even when the privatization of its constructor, we can also visit its constructor is called by violence, so running more test class The results are:

It can be seen acquired by calling the getInstance method instance is the same, but acquired by reflecting instance is different, in violation of the Singleton design mode of thinking, then how should we solve it? We only need to add a judge to the private constructor:

At this point, we start the test class again, to obtain the following results:

Of course, to solve the problem using reflection technology to capture the different instances.

Serialization and deserialization art acquired different instances:

If we singleton class implements Serializable interface, then this class can be serialized and deserialized, the test code is as follows:

Results are as follows:

We find references after been to serialization and de-serialization of objects was altered, and apparently also in violation of the idea of ​​Singleton design pattern after tracking readObject source, found this method will be the first to write a newInstance, and then determine whether this object this method has readResolve whether, if there is no, then return to this direct the newInstance, if present, is invoked readResolve this method, this method returns the value returned to the source fragment readObject follows:

From the above, we only need to add a method to this readResolve Singleton in this class.

Enable test class again, the results are as follows:

Author: Mazin
https://my.oschina.net/u/3441184/blog/884767

Published 50 original articles · won praise 1706 · Views 2.22 million +

Guess you like

Origin blog.csdn.net/zl1zl2zl3/article/details/105298523