# Template Method

> Define the skeleton of an algorithm in a base class — lock down the structure, let subclasses fill in the specific steps.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/template-method/

---

## Description
**Intent**: Enforce a consistent algorithm structure while letting subclasses customize individual steps without touching the overall flow.

**Context**: You have a data mining pipeline, report generator, or multi-step workflow that always follows the same sequence (open → extract → parse → analyze → close) but with different implementations for each source (CSV vs. XML vs. PDF). Duplicating the structure in every subclass is fragile.

**Solution**: Define the overall algorithm sequence in a base class `templateMethod()`. Mark each customizable step as `abstract` or overridable. Subclasses override only the steps they care about; the skeleton stays fixed in the base class.


## Use Cases
Use when multiple classes share the same algorithm structure but differ in implementation details — data parsers, report generators, test frameworks, build pipelines.



## Implementation Example

```javascript
class DataMiner {
  mine(path) {
    this.openFile(path);
    this.extractData();
    this.parseData();
    this.closeFile();
  }
  openFile(path) { console.log(`Opening ${path}`); }
  closeFile() { console.log("Closing file"); }
  extractData() {} // Abstract
  parseData() {} // Abstract
}

```



## Trade-offs


### Advantages

- Algorithm structure is defined once — subclasses only override what they need to.

- Duplicate scaffolding code gets pulled up into one place.




### Considerations & Drawbacks

- Subclasses are tightly coupled to the base class structure — changes to the skeleton ripple down.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/template-method)

