Lazy Initialization Pattern
Problem
The creation of some objects is sometimes costly.
Solution
Delay the creation of such an object until it is first needed. Augment the creation methods to not run until the object is used for the first time.
Related Patterns
- Factory Method
- Abstract Factory
Discussion
Lazy Initialization will often speed the start-up of a system, as it avoids pre-allocation of large objects. However, it can have negative effects on the overall performance as the expensive object creation pops up when those are needed. The key benefit is that you can often avoid the creation of objects that are never used.
Examples
One example is a database connection object. We can create the object to hold the connection, but the connection will not be made until we actually need to query or insert to the database. If we never actually need to interact with the database, the connection will not be made.
Code
This is a Python snippet that delays the initialization of a Fruit until it is actually used.
class Fruit(obj): def __init__(self, sort): self.sort = sort class Fruits(obj): def __init__(self): self.sorts = {} def get_fruit(self, sort): if sort not in self.sorts: self.sorts[sort] = Fruit[sort] return self.sorts[sort] if __name__ == '__main__': fruits = Fruits() print fruits.get_fruit('Apple') print fruits.get_fruit('Banana')