---
name: template-method
description: This skill should be used when the user asks about "template method pattern", "when to use template method", "implement template", "algorithm skeleton", "hook methods", or mentions needing to define an algorithm structure with customizable steps.
version: 1.0.0
---

# Template Method Pattern

## What Is It
The Template Method pattern defines the skeleton of an algorithm in a base class, letting subclasses override specific steps without changing the algorithm's structure. It provides a framework for algorithm customization.

## When to Use
- **Data processing pipelines** - ETL with different formats
- **Report generation** - Same structure, different formats (PDF, HTML, CSV)
- **Game loops** - Common structure, game-specific logic
- **API clients** - Same flow, different endpoints
- **File parsers** - Common parsing flow, format-specific details
- **Testing frameworks** - Setup, execute, teardown pattern

## When NOT to Use
- **Simple algorithms** - No need for customization
- **Steps vary dramatically** - Use Strategy instead
- **Few variations** - Inheritance overhead not worth it
- **Runtime step selection** - Use Strategy or Command

## How to Implement

### Implementation Steps
1. Create an abstract class with the template method
2. The template method calls primitive operations in order
3. Implement common operations in the base class
4. Make abstract the operations that must vary
5. Optionally provide hook methods for extension points

### TypeScript Implementation

```typescript
// Abstract class with template method
abstract class DataParser {
  // Template method - final algorithm
  parse(filePath: string): void {
    this.readFile(filePath);
    const data = this.parseData();
    this.validate(data);
    this.save(data);
    this.logCompletion();
  }

  protected abstract readFile(path: string): void;
  protected abstract parseData(): unknown;
  protected validate(data: unknown): void { /* default impl */ }
  protected abstract save(data: unknown): void;

  // Hook method
  protected logCompletion(): void {
    console.log('Parse complete');
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/template-method.ts` - Basic implementation with data processing
- `examples/template-method-advanced.ts` - Real-world example with build system

## Related Patterns
- **Strategy** - Strategy changes entire algorithm; Template Method changes parts
- **Factory Method** - Often used within Template Methods
- **Command** - Command is one operation; Template Method is an algorithm
