Template Method Pattern

The Template Method Pattern is a behavioral design pattern that allows you to define the skeleton of an algorithm in a superclass but let subclasses override specific steps of the algorithm without changing its structure.

In Angular, this pattern can be applied in various scenarios, such as defining a common structure for components with some variability in behavior.

Here's a simplified example of how you can implement the Template Method Pattern in Angular:

Let's say you have a base component called BaseComponent which provides a template for rendering some content.

This component defines the overall structure of the content but leaves certain parts to be implemented by subclasses.

// base-component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-base',
  template: `
    <div class="base-container">
      <h2>{{ getTitle() }}</h2>
      <div class="content">
        {{ getContent() }}
      </div>
    </div>
  `,
})
export abstract class BaseComponent {
  abstract getTitle(): string;
  abstract getContent(): string;
}

In this BaseComponent, we define a template for rendering a title and content. However, the actual title and content are left abstract, meaning they must be implemented by subclasses.

Now, let's create a concrete subclass SubComponent that extends BaseComponent and provides implementations for getTitle() and getContent():

// sub-component.ts
import { Component } from '@angular/core';
import { BaseComponent } from './base-component';

@Component({
  selector: 'app-sub',
  template: ''
})
export class SubComponent extends BaseComponent {
  getTitle(): string {
    return 'SubComponent Title';
  }

  getContent(): string {
    return 'This is the content of SubComponent';
  }
}

Now, SubComponent extends BaseComponent and provides concrete implementations for getTitle() and getContent().

Finally, you can use SubComponent in your Angular application:

<!-- app.component.html -->
<app-sub></app-sub>

When you run your Angular application, it will render the content defined by SubComponent, following the structure defined in BaseComponent. This way, you can reuse common functionality defined in BaseComponent while allowing flexibility for customization in subclasses, adhering to the Template Method Pattern.

Last updated