Strategy pattern — angular

Implementing Strategy Pattern using Angular

Mariodante
3 min readOct 25, 2023

The Strategy pattern is a behavioral design pattern that enables selecting an algorithm at runtime. In this article, I’m going to implement this pattern in an Angular application. The scenario where it’ll explain is simple: In our application, we’ll have a greeting service and two strategies — English and Spanish.

This explanation will be very short, in additional, I’ll share a final github repository.

Step 1: Define the Greeting Strategy

We start by defining an abstract class that represents our strategy, this class :

GreetingStrategy class

This class will act as our ‘contract’, all different Greeting in the different languages should implent their greet() way. Currently, We have two (english and spanish) but in the future, maybe you want to implement a new one — kinglon- that the way to say hello is ‘nuqneH’.

Step 2: Implement the Strategies

Next, we implement two concrete strategies:

Differents way to greeting

Step 3: Create the Greeting Service

We then create a GreetingService which will use one of these strategies:

Step 4: Use the Greeting Service in a component

Finally, We need to use our service on a component. I created a new component called reusablecomponent, the idea is that this component implements the two ways to greetings, then our html templates should looks like:

This components receive a @input called language, this parameter will be used to create the strategy (and calle it) and a public parameter called greet, that shows us the correct ‘greeting way’ according to language selectd.

the component’s code is the next one:

component’s code

In the code, we receive the language parameter and create the correct way using the strategy implementation.

Finally, to use reusablecomponent, We just to include it in others component’s templates like this:

This is the output that you can see in your browser:

Browser messages

And that’s it! With this setup, you can now easily switch between different greeting strategies in your Angular application. The Strategy pattern gives you the flexibility to change the behavior of your code dynamically.

You can check the related code using downloading the code:

https://github.com/mariodantemariani/strategy-pattern-angular

--

--

No responses yet