...
/Solution: Lazy-Load a Heavy Service Only When First Used
Solution: Lazy-Load a Heavy Service Only When First Used
Use the get trap to instantiate a service only when it’s first accessed.
We'll cover the following...
We'll cover the following...
Solution explanation
Lines 2–10: We define the
DataServiceclass to simulate an expensive dependency.Its constructor logs a message when initialized, representing heavy setup work.
The
fetchData()method represents an operation that other modules will eventually call.
Lines 13–26: The
createLazyService()function builds the Proxy responsible for lazy initialization.A variable
instanceholds the actualDataServiceinstance, starting asnull.The ...