Techumber
Home Blog Work

JavaScript Design Patterns Strategy

Published on June 8, 2021

Strategy Pattern is very useful when we want to encapsulate a group of closely related Algorithms.

Let’s take a example.

Lets say you are given a list of string contains {airline} {type} {totalMiles} and we are asked to design class for this.

const input = [
	"AA economy 1201",
	"Sprit business 600"
]

We need to return prices in a list.

We are also given Airline and charges for each class per mile.

AA => {  economy: 1.23 per mile, premium: 3.01 per mile  }
Sprit => {  economy: 1.1 per mile, premium: 2.21 per mile  }
....

We may have more airline in future.

I will create class for each airline


class AA {
	prices = {
		economy: 1.23,
		premium: 3.01
	}
	calc(miles) {
		return this.prices[type] * miles;
	}
}


class Sprit {
	prices = {
		economy: 1.1,
		premium: 2.21
	}
	calc(type, miles) {
		return this.prices[type] * miles;
	}
}

Now we will build our main Strategy class.


class AirLineFair {
	airline = null;
	setStrategy(airline) {
		this.airline = airline;
	}
	calc(type, miles) {
		return this.airline.calc(type, miles);
	}
}

To use this


const aa = new AA();
const sprit = new Sprit();

const airLineFair = new AirLineFair();
airLineFair.setStrategy(aa);
airlineFair.calc("economy", 1201); // This would return the result for AA.

airLineFair.setStrategy(sprit);
airlineFair.calc("business", 600; // This would return the result for Sprit.

We could add more functionality and airlines to this.

We can do this with simple Object also but In Oops you may get questions like this.