[pattern] Lazy initialization


In computer programming, 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.

This is typically accomplished by maintaining a flag indicating whether the process has taken place. Each time the desired object is summoned, the flag is tested. If it is ready, it is returned. If not, it is initialized on the spot. In multithreaded code, access to the flag must be synchronized to guard against a race condition.


The "lazy factory"[edit]

In a software design pattern view, lazy initialization is often used together with a factory method pattern. This combines three ideas:

- using a factory method to get instances of a class (factory method pattern)

- storing the instances in a map, so you get the same instance the next time you ask for an instance with same parameter (Multiton pattern, similar to the singleton pattern)

- using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern).

Source: http://en.wikipedia.org/wiki/Lazy_initialization Version date: 2014-02-24
Visit also