Home > Back-end >  A little doubt about the singleton pattern (the definition of singleton and prevent reflection)
A little doubt about the singleton pattern (the definition of singleton and prevent reflection)

Time:09-30

Recently in Java, the definition of singleton pattern is a class corresponding to one (only one class and one instance) or each class only one (the each class has one instance)?
If I wrote a class loader, and then load the singleton class, then through the hands to do something in the constructor and also can prevent reflection. My question is, for example, I used two different class loaders loaded twice singleton class, reflect every time the getInstance method, and then every singleton class instantiation again, that this is the two classes, there are two cases, this accords with the definition of singleton? If you do not accord with a reflection of how to prevent this?

CodePudding user response:

Theory is A kind of corresponding example, although your custom Class loader to load many times to the same Class can do each Class is only one, but the Class is loaded in memory belong to different Class object, which is A of the same Class X by the Class loader for the Class object and Class loader B X X Class object is different, and not visible to each other, so for the Class loader A ClassX or single instance (because it can't see the Class loader B ClassX), in the same way, for Class loaders, ClassX still single instance, so it should be in conformity with the single instance definition,
And if not assigned to load the class parents, in addition to your custom class loader loaded classes meet you, the rest of the class loader is not know it, unless you are all business class in your custom class loader loads, or other business class loader loads to use single instance of the class, you will be thrown couldn't find a kind of abnormal, so even if you many times by multiple class loaders load a single instance class, impact is not big, the same class loader business class can only see their own class loaders loading single instance of the class, can't see the other class loaders loading the single instance of class, have a purpose?

  • Related