Pattern: Lazy
Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
Purpose of .NET implementation
You want to access one object that is difficult to create.
But you do not know when will be created.
You can use the Lazy pattern to create the object only when it is needed.
The Lazy of generic T class provides a way to defer the creation of an object until it is actually needed, allowing you to avoid the cost of creating the object until it is actually required.
Example in .NET :
Lazy
Lazy example for Pattern Lazy
namespace Lazy;
internal class LazyDemo
{
public DateTime dateTimeConstructClass =DateTime.Now;
public Lazy<DateTime> DateTimeLazy = new(() =>
{
Console.WriteLine("Lazy<DateTime> is being initialized ONCE!");
return DateTime.Now;
});
}
See Source Code for Microsoft implementation of Lazy
SourceCode _defaultLaunchProfile = new Lazy of LaunchProfileSourceCode Lazy
SourceCode Lazy of IStreamingFindUsagesPresenter
Learn More
C2WikiWikipedia
Homework
Implement a lazy initialization of a logger that logs to a file and to a console.
The logger should be created only when it is needed.