Delayed Initialization
In object-oriented programming we ensure that objects are well constructed before any method calls. We encapsulate, ensure proper state transitions, and preserve the object’s invariants. This works well most of the time, but when parts of an object’s internals are heavyweight resources, we’ll benefit if we postpone creating them. This can speed up object creation, and the program doesn’t expend any effort creating things that may not be used.
The design decision to postpone creating part of an object should not burden the object’s users—it should be seamless. Let’s explore some ways to design lazy initialization.
A Familiar Approach
In the following example, we will craft a way to delay the creation of a heavyweight instance. ...
Get Functional Programming in Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.