Design patterns are proven, practical, and reusable solutions fit for tackling specific problems in software development. They not only help us avoid pitfalls in organizing our applications, but also provide a shared glossary to describe our implementation and understand each other as fellow developers. There are dozens of patterns already discovered and I am pretty sure you are using at least some of them, even if you do not identify them as a design pattern (Hello constructor pattern 👋).

Design patterns are grouped into three categories: Creational, structural, and behavioral. In this article, I would like to focus on one of the behavioral patterns, the strategy (a.k.a. policy) pattern, and how we benefit from it in ABP Framework frontend. I am hoping this article will help you understand and use both the pattern and ABP features more effectively than ever.

What is Strategy Pattern?

I like explaining concepts with code examples and, since we shall see the use of strategy pattern in Angular later, the code examples here are in TypeScript. That being said, JavaScript implementation is quite similar.

So, let's check out what the Avengers would look like, if they were represented by a class:

class Hero {
  constructor(public name: string, public weapon?: string) {}
}

class Avengers {
  private ensemble: Hero[] = [];
  
  private blast(hero: Hero) {
    console.log(`${hero.name} blasted ${hero.weapon}`);
  }
  
  private kickAndPunch(hero: Hero) {
    console.log(`${hero.name} kicked and punched`);
  }
  
  private shoot(hero: Hero) {
    console.log(`${hero.name} shot ${hero.weapon}`);
  }
  
  private throw(hero: Hero) {
    console.log(`${hero.name} threw ${hero.weapon}`);
  }
  
  recruit(hero: Hero) {
    this.ensemble = this.ensemble
      .filter(({name}) => name === hero.name)
    	.concat(hero);
  }
  
  fight() {
    this.ensemble.forEach(hero => this.attack(hero));
  }
  
  attack(hero: Hero) {
    switch(hero.name) {