Template Method
Last updated
Last updated
Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.
The Template Method design pattern is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.
The Template Method Design Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses.
It allows subclasses to redefine certain steps of the algorithm without changing its structure.
In JavaScript, you can implement this pattern using object-oriented programming techniques.
In this example:
Game
is an abstract class defining the template method play()
which outlines the algorithm and calls the initialize()
, start()
, and end()
methods.
initialize()
and end()
methods have default implementations, while start()
is an abstract method that must be implemented by subclasses.
Football
and Chess
are concrete subclasses that extend Game
and provide their own implementation for the start()
method.
When play()
is called on instances of Football
or Chess
, it executes the algorithm defined in the Game
class, but with the specific start()
method implemented in the respective subclass.
This pattern allows you to define a common algorithm structure in a superclass while enabling subclasses to provide their own implementations for specific steps of the algorithm.