There are four common ways of implementing the lazy load design pattern:
lazy initialization; a
virtual proxy; a
ghost, and a
value holder. Each has its own advantages and disadvantages.
Lazy initialization With lazy initialization, the object is first set to null. Whenever the object is requested, the object is checked, and if it is null, the object is then immediately created and returned. For example, lazy loading for a widget can be implemented in the
C# programming language as such: private int _myWidgetID; private Widget _myWidget = null; public Widget MyWidget { get { if (_myWidget == null) { _myWidget = Widget.Load(_myWidgetID); } return _myWidget; } } Or alternatively, with the
null-coalescing assignment operator ??= private int _myWidgetID; private Widget _myWidget = null; public Widget MyWidget { get => _myWidget ??= Widget.Load(_myWidgetID); } This method is the simplest to implement, although if null is a legitimate return value, it may be necessary to use a placeholder object to signal that it has not been initialized. If this method is used in a
multithreaded application, synchronization must be used to avoid
race conditions.
Virtual proxy A virtual proxy is an object with the same interface as the real object. The first time one of its methods is called it loads the real object and then delegates.
Ghost A ghost is the object that is to be loaded in a partial state. It may initially only contain the object's identifier, but it loads its own data the first time one of its properties is accessed. For example, consider that a user is about to request content via an online form. At the time of creation, the only information available is that content will be accessed, but the specific action and content is unknown. An example in
PHP: $userData = array ( "UID" = > uniqid(), "requestTime" => microtime(true), "dataType" => "", "request" => "" ); if (isset($_POST['data']) && $userData) { // ... }
Value holder A
value holder is a generic object that handles the lazy loading behavior, and appears in place of the object's data fields: private ValueHolder valueHolder; public Widget MyWidget => valueHolder.GetValue(); == See also ==