Today, the phone interview when asked, Google a bit
Original source:
http://blog.csdn.net/lws332969674/article/details/8125893
One, the reflection technology in Java can get all the methods of the class, member variables, but also access to the private construction method, so that the private constructor used in singleton mode is called to produce multiple instances, write code test.
[Java]View Plaincopyprint?
- Package test;
- Import Java.lang.reflect.Constructor;
- Public class Singetontest {
- private static singetontest singleton = null;
- private int s = 0;
- //Construction method is private
- Private Singetontest () {}
- //Synchronous Get instance method
- public static synchronized singetontest getinstance () {
- ///Lazy Mode single-case method
- if (null = = Singleton) {
- Singleton = new Singetontest ();
- }
- return singleton;
- }
- public int GetS () {
- return s;
- }
- public void sets (int s) {
- THIS.S = s;
- }
- /**
- * @param args
- */
- public static void Main (string[] args) {
- try {
- Constructor con = singetontest. Class.getdeclaredconstructor ();
- Con.setaccessible (true);
- //Get an instance by reflection
- Singetontest SingetonTest1 = (singetontest) con.newinstance ();
- Singetontest singetonTest2 = (singetontest) con.newinstance ();
- //General method to get an instance
- Singetontest singetonTest3 = Singetontest.getinstance ();
- Singetontest singetonTest4 = Singetontest.getinstance ();
- //Test output
- System.out.println ("Singetontest1.equals (SINGETONTEST2):" + singetontest1.equals (singetonTest2));
- System.out.println ("Singetontest3.equals (SINGETONTEST4):" + singetontest3.equals (SINGETONTEST4));
- System.out.println ("Singetontest1.equals (SINGETONTEST3):" + singetontest1.equals (SINGETONTEST3));
- Singetontest1.sets (1);
- Singetontest2.sets (2);
- Singetontest3.sets (3);
- Singetontest4.sets (4);
- System.out.println ("1:" + singetontest1.gets () + "2:" + singetontest2.gets () + "3:" + singetontest3.gets () + "4:" + singetontest4.gets ());
- } catch (Exception e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- }
- }
Test results:
Singetontest1.equals (SINGETONTEST2): false
Singetontest3.equals (SINGETONTEST4): True
Singetontest1.equals (SINGETONTEST3): false
1:1 2:2 3:4 4:4
The two instances generated by the reflection technique are different, and the two instances obtained by the conventional method are the same (that is, the same instance, single case).
Second, to prevent the reflection of the failure of the singleton mode, the constructor called when the processing, when the constructor is called the 2nd time throw an exception! Modify the construction method as follows:
[Java]View Plaincopyprint?
- Private static Boolean flag = false;
- //Construction method is private
- Private Singetontest () {
- if (flag) {
- flag =!flag;
- }
- else{
- try {
- throw New Exception ("Duplicate instance Create error!" + singetontest. Class.getname ());
- } catch (Exception e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- }
- }
Third, some thinking
1) Singleton mode is to ensure that only one instance of a class, the whole system can only have one instance of their own creation. Apply issues such as database connections or individual queue processing.
2) Single pattern construction, lazy mode with time to change space (when used in the production of instances, every time to judge); The lazy mode takes space to change the time, creates the instance directly, later does not need to judge directly to use.
3) Lazy Mode thread safety problem, get the instance method to add synchronized to synchronize.
4) Java's reflection technology is not used for instance creation, and reflection is primarily used for spring IOC, Hibernate, and white box testing.
---------------------------------------------------------I'm enumerating the split lines-------------------------------------------------------
You can use enumerations to prevent reflection from destroying a singleton model (Ps:java enumeration is thread-safe)
from:http://blog.csdn.net/tounaobun/article/details/8514989
JDK1.5 and later, the third method of implementing Singleton was added. Just write an enumeration type that contains a single element.
Java code
- Public enum Adam {
- INSTANCE; //Only one element
- public void leavethebuilding () {;;;}
- }
The advantage of using this approach is that it prevents multiple instantiations, providing a serialization mechanism for free, even in the face of complex serialization or reflection of a rooster.
When you try to invoke the constructor of an enumerated type by reflection (the default constructor is private), if you call the Setaccessible (True) method, the IllegalArgumentException will be thrown:
Java code
- Exception in thread "main" java.lang.IllegalArgumentException:Cannot reflectively create enum objects
- At Java.lang.reflect.Constructor.newInstance (Unknown Source)
- At Org.reflect.Test.main (Test.java:)
For the first two singleton modes, in order for the Singleton to serialize, in addition to implementing the markup interface serializable, you need to add a method similar to the following to prevent the "fake" singleton class from being generated when deserializing:
Java code
- Private Object Readresolve () {
- return INSTANCE;
- }
For enumeration types, superfluous is not necessary at all. This mechanism is already available because of the enumeration type.
Java Reflection Break Single-instance mode