---
name: lazy-initialization
description: This skill should be used when the user asks about "lazy initialization", "lazy loading", "defer initialization", "on-demand creation", "initialize on first use", or mentions delaying expensive object creation.
version: 1.0.0
---

# Lazy Initialization Pattern

## What Is It
Lazy Initialization defers object creation until first use. The object is created on demand rather than at construction time, improving startup performance and resource usage.

## When to Use
- **Expensive resources** - Database connections, large objects
- **Conditional usage** - May not always need the object
- **Startup performance** - Reduce initialization time
- **Memory optimization** - Avoid loading unused data

## When NOT to Use
- **Cheap to create** - Overhead exceeds benefit
- **Always needed** - Deferred creation adds complexity
- **Timing sensitive** - First access must be instant
- **Thread safety complex** - Synchronization overhead

## How to Implement

```typescript
class Lazy<T> {
  private value: T | null = null;
  private initialized = false;

  constructor(private factory: () => T) {}

  get(): T {
    if (!this.initialized) {
      this.value = this.factory();
      this.initialized = true;
    }
    return this.value!;
  }

  isInitialized(): boolean {
    return this.initialized;
  }
}

// Usage
const expensiveResource = new Lazy(() => createHeavyObject());

// Not created yet
if (needsResource) {
  const resource = expensiveResource.get(); // Created now
}
```

## Code Examples
- `examples/lazy-initialization.ts` - Basic implementation
- `examples/lazy-initialization-advanced.ts` - Real-world usage

## Related Patterns
- **Proxy** - Virtual proxy uses lazy loading
- **Singleton** - Often uses lazy initialization
- **Factory Method** - Can combine with lazy creation
