Skip to main content

Template Method Design Pattern

Structural: Template Method



What is the Template Method design pattern in JavaScript?

View Answer:
Interview Response: It's a behavioral pattern that defines a program skeleton in a method, deferring some steps to subclasses, which lets subclasses redefine certain steps of an algorithm without changing its structure.

Technical Response: The Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the base class but lets subclasses override specific steps of the algorithm without changing its structure. In JavaScript, you can use a base class with methods that subclasses can override.

Code Example:



This pattern's objects are as follows:

AbstractClass -- example code: datastore

  • It provides a way for clients to use the template method.
  • It uses the template method to define the basic steps of an algorithm.
  • It provides hooks (through method overriding) for a client developer to use in implementing the Steps.

ConcreteClass -- example code: MySQL

  • carries out the primitive Steps described in AbstractClass.

Here's an example of how to implement the Template Method pattern in modern JavaScript:

// This is the base class that contains the template method and common steps.
class Bread {
// This is the template method.
bakeBread() {
this.mixIngredients();
this.firstProving();
this.shapeDough();
this.secondProving();
this.bake();
}

// These are the steps that are the same for all breads.
mixIngredients() {
console.log('Ingredients mixed for standard bread.');
}

firstProving() {
console.log('First proving completed.');
}

shapeDough() {
throw new Error('You have to implement the method shapeDough!');
}

secondProving() {
console.log('Second proving completed.');
}

bake() {
throw new Error('You have to implement the method bake!');
}
}

// This is a concrete class that implements the varying steps.
class SourdoughBread extends Bread {
shapeDough() {
console.log('Dough shaped into a rustic loaf for sourdough bread.');
}

bake() {
console.log('Sourdough bread baked at 230 degrees Celsius for 40 minutes.');
}
}

// This is another concrete class that implements the varying steps.
class Baguette extends Bread {
shapeDough() {
console.log('Dough shaped into a long, thin cylinder for baguette.');
}

bake() {
console.log('Baguette baked at 240 degrees Celsius for 20 minutes.');
}
}

// Usage:
let bread = new SourdoughBread();
bread.bakeBread();

bread = new Baguette();
bread.bakeBread();

When you run this program, you'll see the steps of baking bread printed out. The steps that are the same for all breads are implemented in the base class, while the steps that can vary depending on the type of bread (shaping the dough and baking) are implemented in the subclasses. The bakeBread method in the base class is the template method, and it dictates the sequence of steps for baking bread.


What pattern category does the template method pattern belong to?

View Answer:
Interview Response: The template method pattern belongs to the behavioral design pattern category in JavaScript, which focuses on communication between objects and how they interact.

Can you give an example of when to use the Template Method?

View Answer:
Interview Response: You can use the Template Method when you want to let clients extend only particular steps of an algorithm, but not the whole algorithm or its structure.

Technical Response: The template method pattern is useful when you want to define a skeletal structure of an algorithm in JavaScript and allow subclasses to customize some steps.

When to Use the Template Method Pattern:

  • The template method pattern solves the problem by employing an algorithm with various versions. You need to divide your method into additional steps implemented in the abstract class when the different implementations share them. On the other hand, we implement the various steps in the concrete classes.
  • Another compelling use case for this approach is when you have copied and pasted code (private functions) between various classes.
  • Finally, you can employ this strategy if most of your classes exhibit similar tendencies.


What are some of the benefits of using the Template Method pattern?

View Answer:
Interview Response: Benefits of using the Template Method pattern in JavaScript include promoting code reuse, reducing duplication, and providing a clear and flexible structure for algorithms.

Technical Response: Benefits of the Template Method Pattern

  • It's relatively easy to create a concrete implementation of an algorithm because you're removing common parts of the problem domain using an abstract class.
  • Clean code because you avoid duplicate code.
  • Ever cleaner code because you separate the algorithm into private methods or functions that are simpler and easier to test.


What are some disadvantages of employing the Template Method design pattern?

View Answer:
Interview Response: Disadvantages of using the Template Method pattern in JavaScript include increased complexity due to the added abstraction layer, and reduced flexibility in the overall design.

Technical Response: Drawbacks of the Template Method Pattern.

  • You may violate the Liskov Substitution Principle by suppressing a default step implementation through a subclass.
  • Some clients may be the only reason the template pattern imposes a specific design.
  • The template design is more adaptable than other patterns, and modifications at the high or low level might disrupt implementation, making maintenance difficult.


Are there any alternatives to using the Template Method?

View Answer:
Interview Response: Yes, some alternatives to the Template Method pattern in JavaScript include the Strategy pattern, the Command pattern, and the Decorator pattern.

Technical Response: Yes, there are several alternatives to the Template Method pattern in JavaScript, including the Strategy pattern, which uses composition instead of inheritance, the Command pattern, which encapsulates requests as objects, and the Decorator pattern, which adds functionality to objects dynamically at runtime.

How does the Template Method contribute to code reuse?

View Answer:
Interview Response: It promotes code reuse by encapsulating common behavior in a superclass while allowing subclasses to implement specific behavior.

What are the key components of the Template Method pattern?

View Answer:
Interview Response: The key components are an abstract class with a template method containing the algorithm skeleton, and concrete classes that implement these operations.

Code Example:

// Abstract base class
class AbstractClass {
// Template method
templateMethod() {
this.primitiveOperation1();
this.primitiveOperation2();
}

// Default operation
primitiveOperation1() {
console.log('Primitive operation 1 from AbstractClass');
}

// Abstract operation
primitiveOperation2() {
throw new Error('You have to implement the method primitiveOperation2!');
}
}

// Concrete subclass
class ConcreteClass extends AbstractClass {
// Overriding abstract operation
primitiveOperation2() {
console.log('Primitive operation 2 from ConcreteClass');
}
}

// Usage:
let instance = new ConcreteClass();
instance.templateMethod();

In this code:

  • AbstractClass is the abstract base class. It contains the template method (templateMethod), a default step method (primitiveOperation1), and an abstract step method (primitiveOperation2).

  • templateMethod is the template method. It calls primitiveOperation1 and primitiveOperation2 in a specific order.

  • primitiveOperation1 is a default step method, which is defined in the base class and is the same for all subclasses.

  • primitiveOperation2 is an abstract step method, which must be implemented by each subclass.

  • ConcreteClass is a concrete subclass that inherits from AbstractClass and implements primitiveOperation2.

When you run this code, the output demonstrates that the template method has dictated the order of execution of the operations and that the operation overridden in the subclass has been successfully executed.


How does the Template Method maintain the Open/Closed Principle?

View Answer:
Interview Response: It maintains the Open/Closed Principle by allowing new steps to be added in subclasses without modifying the abstract class or the algorithm's structure.

How do the Template Method and the Strategy Pattern differ?

View Answer:
Interview Response: The Strategy Pattern uses composition to change parts of the algorithm, while the Template Method uses inheritance to modify parts of the algorithm.

What is a potential downside of the Template Method pattern?

View Answer:
Interview Response: One downside is that you might create a superclass with a large template method that's difficult to understand and maintain.

Can the Template Method pattern lead to problems in JavaScript due to its prototypal inheritance?

View Answer:
Interview Response: Yes, Template Method pattern can lead to problems due to JavaScript's prototypal inheritance, such as difficulty with method overriding, lack of clear abstract classes, and potential confusion with this context. Note: It should be noted that ES6 classes are the best way to implement the Template Method.

Is it common to use the Template Method pattern in functional programming?

View Answer:
Interview Response: No, it's less common since functional programming discourages the use of mutable state and often prefers composition over inheritance.

Can the Template Method pattern be used with JavaScript's ES6 class syntax?

View Answer:
Interview Response: Yes, the ES6 class syntax supports the key concepts needed for the Template Method pattern, including inheritance and method overriding.

Code Example:

// Abstract class
class AbstractClass {
// Template method
templateMethod() {
this.primitiveOperation1();
this.primitiveOperation2();
}

primitiveOperation1() {
console.log('Primitive operation 1 is running...');
}

primitiveOperation2() {
throw new Error('Method \'primitiveOperation2\' is not implemented');
}
}

// Concrete class
class ConcreteClass extends AbstractClass {
primitiveOperation2() {
console.log('Primitive operation 2 is running...');
}
}

// Usage:
const concreteInstance = new ConcreteClass();
concreteInstance.templateMethod();

In this example, AbstractClass is the abstract class with a template method (templateMethod) and two primitive operations. ConcreteClass is a concrete class that extends AbstractClass and implements primitiveOperation2. This code runs the template method on an instance of ConcreteClass, which executes the two primitive operations in order.