Implementation of Strategy pattern in Angular 2 and more

Posted By : Tajinder Singh | 29-Jan-2019

Introduction:

Strategy Patterns are making patterns for logic or strategy in multiple algorithms and choose one among them. We use strategy patterns to make our code optimized. 

Design patterns are ways of standardized resources implementations into an application. The biggest motivation to use patterns is the increase in efficiency and help on code maintenance in the future.

There are a lot of design patterns are being used outside. From this big list, we have Strategy, which is maybe the simplest among them. It mostly appears, when we need to differentiate some part of our algorithm to process different client requests, but at the same time, we want to reach a common final objective.

Analyzing a situation

Mohan is a little chubby. His doctor recommended him to start exercising during the week, at least doing what he likes the most. Mohan loves doing three things when it comes to sports: running, soccer and gymming. His wife, Ruchi, is working and because of that he leaves to go work out, so he downloaded a TypeScript program to help him let his wife knows what he has chosen to do.

After running the program, Ruchi received the response that Mohan decided to play soccer with his friends. Mohan knows design patterns and realized this was not the best way of implementing this program.

 

enum FavoriteWorkout {
  Running, Soccer, Gym
}

class Person {
  public name: string;
  public favouriteWorkout: FavouriteWorkout;

  constructor(name: string, favouriteWorkout: FavouriteWorkout) {
    this.name = name;
    this.favouriteWorkout = favouriteWorkout;
  }

  workout(): void {
    console.log(`${ this.name } decided to:`);
    if(this.favouriteWorkout == FavouriteWorkout.Running) {
      console.log('Go running in park.')
    } else if (this.favouriteWorkout == FavouriteWorkout.Soccer) {
      console.log('Play soccer with your friends.')
    } else if (this.favouriteWorkout  == FavouriteWorkout.Gym) {
      console.log('Go to the gym.')
    }
  }

}

// Execute
const Mohan = new Person('Mohan', FavouriteWorkout.Soccer)
Mohan.workout() // Mohan decided to: Play soccer with friends.

Is using IFs in his code a bad idea?

Conditional structures are the basis of programming languages. The structure IF/ELSE is present in, pretty much, every programing language. However, just because they are there, it does not mean they are the only choice left for us. Imagine Mohan discovered a new favorite sport. Adding them to the program would make code harder to read, hence harder to maintain Mohan could add side effects to his program.
and, we have a Strategy pattern. It allows us to encapsulate each one of Mohan’s favorite sports in a different class. We need to guarantee that each sport will tell the user which option Mohan took. How to change that? Using Interfaces.

Let us start by declaring an interface FavoriteWorkout. Every class which implements it must contain the method start(), responsible for showing the notification to Ruchi. 

Now, we may need to refactor our sports. Here, the idea is that each FavouriteWorkout is encapsulated in its own class, which implements the interface we’ve just created, and the notifications on the console are being made by the function start(), that makes part of the contract signed by our class when it implements our interface.

 

export interface FavouriteWorkout {
  start(): void;
}

What is the benefit of doing all this?

Suppose now Mohan decided to play volleyball with the other sports that he has already practiced. Instead of worrying on modifying many IFs through his code, he only should add a new Class to the program:

 

import { FavouriteWorkout } from './sports.ts'

export class Volleyball implements FavouriteWorkout {
  public start(): void {
    console.log('Play volleyball with your friends')
  }
}

Conclusion:

In this blog, I have explained what are Strategy patterns and Design patterns and with the help of an example, I have tried to make strategy pattern understandable and how we can use in our coding skills to improve. I would like to Thank Vijay Kumar Sir for Suggesting me this topic and Motivated me to Write a blog on it.  

About Author

Author Image
Tajinder Singh

Tajinder Singh is a person who faces every challenge with positive approach. He has a creative mind.

Request for Proposal

Name is required

Comment is required

Sending message..