Java – it is better to have a caching mechanism inside or outside the factory class?
My problem is not strictly language - related, it's more like a general programming concept
If I have a factory class with a method to return the parser object, and these parser classes, I know that each iteration cycle does not need to be instantiated multiple times (outside the factory, of course)
In terms of separation of use and object, it is better to create a caching mechanism for all instantiated parsers inside the factory, that is, during or outside the method call, when the method has been called?
Thank you in advance
Solution
Maybe you can define an interface for your factory and then have multiple implementations - an implementation can execute caching internally to ensure that the parser class is instantiated only once Another implementation may not execute caching and provide a new parser object as long as something requires one
Either way, I suggest you try to keep this logic in the factory implementation and use the rest of the applications with the factory interface In this way, if you decide later that you don't want to cache anything or you need to change the way you instantiate the parser, you only need to create an object point in the factory This makes it easy to change the way a parser object is constructed without changing every part of the application that needs a new parser
Again – if you create caching mechanisms that run outside the factory, these mechanisms will spread throughout your code because you must use them every time you want to get a new parser If you decide to change the caching mechanism later, you must touch a lot of code, but if you perform caching in factory, you only need to change the factory implementation