avatarCarlos Caballero

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2506

Abstract

xt contains a <code>Strategy</code> object (<code>concreteStrategyA</code>, <code>concreteStrategyB</code>,…) which implements the interface <code>Strategy</code>. The key interchange consists in implementing a method in context, which changes the instance of strategy. For example: <code>setStrategy</code>.</p><h1 id="a0e6">When to Use the Strategy Pattern</h1><ol><li>When you need to use several algorithms with different variations. You need create a concrete class to implement your algorithm (which can consist of <code>a</code> or <code>some</code> functions).</li><li>When there are conditional statements around several related algorithms.</li><li>When most of your classes have related behaviours.</li></ol><h1 id="b5ce">Advantages of the Strategy Pattern</h1><p id="d968">The Strategy Pattern has several advantages:</p><ul><li>It’s<b> </b>easy to switch between different algorithms<b> </b>(strategies) in runtime because you’re using polymorphism in the interfaces.</li><li>Clean code<b> </b>because you avoid conditional-infested code (not complex).</li><li>More clean code because you separate the concerns into classes (a class to each strategy).</li></ul><h1 id="a2b3">Strategy Pattern: A Basic Implementation Using JavaScript</h1><p id="df6f">I’m going to show you how you can implement this pattern in JavaScript. Remember: Javascript lacks interfaces — you need to program a class called <code>StrategyManager</code>, which is used as the interface:</p><figure id="0437"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*tGC30XtpdyYkVym3.png"><figcaption></figcaption></figure><p id="ddb6">This class contains a private attribute called <code>_strategy</code>, which represents the strategy used. The method <code>doAction</code> will be implemented in each concrete strategy. The strategy pattern differs from the UML in JavaScript in the lack of OOP features in the language.</p><p id="e1f7">The implementation of each concrete strategy is the following:</p><figure id="cdbf"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*21zj2347tZtVXUOp.png"><figcaption></figcaption></figure><p id="3c5f">Note that the concrete method <code>doAction</code> is implemented in each concrete strategy.</p><p id="0cc8">Finally, the context/client must contain the <code>StrategyManager</code> (or strategy interface is the language is OO) to use the concrete strategy:</p><figure id="f780"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*oo2C989f7

Options

3PpWxRQ.png"><figcaption></figcaption></figure><h1 id="a10d">Strategy Pattern: A set of Strategies Using JavaScript</h1><p id="66ea">In the following implementation, our <code>StrategyManager</code> gets more complex, containing a list of algorithms. In this case, you can change the attribute <code>_strategy</code> instead of an array called <code>_strategies</code>.</p><p id="432f">Finally, you add new strategies in the list of strategies using the method <code>addStrategy</code>. The <code>Strategy</code> class has two attributes: 1. Strategy’s name and 2. Algorithm (called <code>handler</code>). The method <code>doAction</code> is used to invoke the concrete algorithm.</p><figure id="9553"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*7Q4QV6fXp_it4IDm.png"><figcaption></figcaption></figure><p id="6455">Finally, the client/context code where we use the concrete strategy:</p><figure id="c0ac"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*LdqQZciDhrvcVS48.png"><figcaption></figcaption></figure><p id="d918">The first part is to create concrete strategies (which can be constructed using the <code>Singleton</code> pattern and the <code>Factory</code><b> </b>pattern) and added to the <code>strategyManager</code><b> </b>(which could be our interface). The next part of the client is selecting the strategy to use — this strategy can be selected using a GUI or CLI from our app.</p><p id="1c81">Finally, note that if an unsupported strategy is selected the system will return an error. This can be used when you want to provide a premium algorithm to your system.</p><p id="cf74">If you liked this article and would like to read similar articles, don’t forget to clap.</p><figure id="e3f5"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*vMyFTOWtr9c252J4X1FW6g.gif"><figcaption>Click and drag to clap more than once. 50 is the limit.</figcaption></figure><p id="4db9">Strategy Pattern can help you avoid complexity in your code when you need to select a concrete algorithm. In this piece, I presented a simple implementation with the language JavaScript, which lacks interfaces. If you use a programming language with an interface you can follow the pattern’s UML.</p><p id="b22c">Most importantly, don’t just implement the pattern as I’ve shown you here. You need to know what the problem is that the pattern resolves and why you should use it. The implementation will vary depending on the programming language.</p></article></body>

Design Patterns: Using the Strategy Pattern in JavaScript

Design patterns series — part 1

There are 23 classical design patterns described in the book Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide a solution to a particular problem, one which is repeated in the software development.

In this piece I will look at the strategy pattern — how it works, how and when it should be apply. This pattern is known as policy in other contexts.

Strategy Pattern: Basic Idea

The strategy pattern is a behavioral design pattern that enables selecting an algorithm at runtime

— Wikipedia

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

— Design Patterns: Elements of Reusable Object-Oriented Software

The main feature of this pattern is that the client has a set of algorithms in which a specific algorithm will be selected for use during runtime. These algorithms are interchangeable between them.

The following code show the classical problem, one in which you need to select a concrete algorithm in your app. In this code, you use the switch control structure of any programming language.

However, it can be more flexible using the Strategy Pattern which takes the following structure:

The UML’s diagram of this pattern:

Each strategy is represented with a concrete object. So, the client/context contains a Strategy object (concreteStrategyA, concreteStrategyB,…) which implements the interface Strategy. The key interchange consists in implementing a method in context, which changes the instance of strategy. For example: setStrategy.

When to Use the Strategy Pattern

  1. When you need to use several algorithms with different variations. You need create a concrete class to implement your algorithm (which can consist of a or some functions).
  2. When there are conditional statements around several related algorithms.
  3. When most of your classes have related behaviours.

Advantages of the Strategy Pattern

The Strategy Pattern has several advantages:

  • It’s easy to switch between different algorithms (strategies) in runtime because you’re using polymorphism in the interfaces.
  • Clean code because you avoid conditional-infested code (not complex).
  • More clean code because you separate the concerns into classes (a class to each strategy).

Strategy Pattern: A Basic Implementation Using JavaScript

I’m going to show you how you can implement this pattern in JavaScript. Remember: Javascript lacks interfaces — you need to program a class called StrategyManager, which is used as the interface:

This class contains a private attribute called _strategy, which represents the strategy used. The method doAction will be implemented in each concrete strategy. The strategy pattern differs from the UML in JavaScript in the lack of OOP features in the language.

The implementation of each concrete strategy is the following:

Note that the concrete method doAction is implemented in each concrete strategy.

Finally, the context/client must contain the StrategyManager (or strategy interface is the language is OO) to use the concrete strategy:

Strategy Pattern: A set of Strategies Using JavaScript

In the following implementation, our StrategyManager gets more complex, containing a list of algorithms. In this case, you can change the attribute _strategy instead of an array called _strategies.

Finally, you add new strategies in the list of strategies using the method addStrategy. The Strategy class has two attributes: 1. Strategy’s name and 2. Algorithm (called handler). The method doAction is used to invoke the concrete algorithm.

Finally, the client/context code where we use the concrete strategy:

The first part is to create concrete strategies (which can be constructed using the Singleton pattern and the Factory pattern) and added to the strategyManager (which could be our interface). The next part of the client is selecting the strategy to use — this strategy can be selected using a GUI or CLI from our app.

Finally, note that if an unsupported strategy is selected the system will return an error. This can be used when you want to provide a premium algorithm to your system.

If you liked this article and would like to read similar articles, don’t forget to clap.

Click and drag to clap more than once. 50 is the limit.

Strategy Pattern can help you avoid complexity in your code when you need to select a concrete algorithm. In this piece, I presented a simple implementation with the language JavaScript, which lacks interfaces. If you use a programming language with an interface you can follow the pattern’s UML.

Most importantly, don’t just implement the pattern as I’ve shown you here. You need to know what the problem is that the pattern resolves and why you should use it. The implementation will vary depending on the programming language.

Programming
JavaScript
Typescript
Angular
Design Patterns
Recommended from ReadMedium