Consider a theoretical factory class containing over a thousand of attributes (models, by example, in a MVC project).
The factory pattern deals to show a scenario snapshot in function a selected level (in a game-like project). The factory has to pass needed components and models to scenarios.
Models and components can be reused by any scenarios, but every scenario can only be initialized only once (it’s impossible to play deals with 2 scenarios).
So, my question is:
Considering that I don’t need every components, I don’t have to initialized the thousand of attributes (because It would be too slow), how can I instantiate the components to pass to scenarios, only if I need it?
I don’t want to make a thousand of factory for each factory (Abstract Factory pattern) and I don’t want to initialised objects in the factory itself, because objects can be reused and I want to avoid copy/paste.
Is there a way to initialized objects on demand, in Java?
I don’t want to receive answer as “It’s a bad conception if you have a thousand of attributes”, I know all of it, but I need to deal with an old system and I would like to reduce the memory usage.
Nothing built-in, no.
I’ve done some lazy-initialization tricks using AOP, e.g., as soon as a property is referenced the first time, run initialization. This could be done for long-running initializations only, for all an object’s properties, arbitrary subsets, etc. depending on needs.
This doesn’t need to be done with AOP, it can be done via normal Java code–but if the Java code has already been written, is coming from a generator outside of your control, etc. it can be problematic.