behavioral
Template Method
Define the skeleton of an algorithm in a base class and let subclasses override selected steps without changing the overall structure.
Problem
Several classes share the same algorithm structure, but some steps need to vary between implementations.
Integration notes
Template Method is useful when you have repeated workflows with a common sequence of steps, such as processing orders, generating reports, and importing data.
Tradeoffs
- Relies on inheritance, which can be less flexible than composition in some designs
- May create a deep class hierarchy if many variations are needed
Languages
typescript, java, python, angular, react, react-native, csharp, dotnet
Platforms
Web, Backend, Mobile, UI kits, Cross-platform systems
Variants
Scenarios
Order processing template
Order processing follows the same high-level steps, but some validation and fulfillment details vary by order type.
Language examples
Core languages
Frameworks and libraries
The template method defines the processing sequence once, while subclasses customize payment and fulfillment steps.
abstract class OrderProcessor {
process(): void {
this.validateOrder();
this.chargePayment();
this.fulfillOrder();
this.sendConfirmation();
}
protected validateOrder(): void {
console.log("Validating order");
}
protected abstract chargePayment(): void;
protected abstract fulfillOrder(): void;
protected sendConfirmation(): void {
console.log("Sending confirmation");
}
}
class PhysicalOrderProcessor extends OrderProcessor {
protected chargePayment(): void {
console.log("Charging payment for physical order");
}
protected fulfillOrder(): void {
console.log("Shipping physical order");
}
}
class DigitalOrderProcessor extends OrderProcessor {
protected chargePayment(): void {
console.log("Charging payment for digital order");
}
protected fulfillOrder(): void {
console.log("Delivering digital product");
}
}
const physical = new PhysicalOrderProcessor();
physical.process();
const digital = new DigitalOrderProcessor();
digital.process();Real-world examples
- Order workflows: E-commerce systems often follow the same order processing steps with variation in payment or shipping handling.
- Report pipelines: Reporting tools typically collect, format, and export data in a fixed sequence with type-specific customizations.
- Import jobs: CSV, JSON, and XML imports often share a pipeline but differ in parsing rules and validation logic.