DEV Community

Cover image for Design Pattern in TypeScript: Strategy Pattern
BhargavMantha
BhargavMantha

Posted on

Design Pattern in TypeScript: Strategy Pattern

Definition - Design Patterns

According to Christopher Alexander- Each Pattern describes a problem that occurs over and over again in our environments, and then describes the core solution to that problem, in such a way that you can use this solution as a million times over without doing it the same way twice

The only difference between the patterns described by Christopher Alexander and the patterns in the case of computer language is that he expresses solutions in terms of Walls and doors Whereas we express them in terms of Objects and Interfaces

A pattern has 4 essential elements:

  1. The Pattern Name
  2. The problem
  3. The Solution
  4. The Consequence

What Design Patterns are not:

  1. designs that are encoded or added into the classes and reused as is like Trees, Stacks ...
  2. Nor are they complex,domain-specific designs for an entire applications or subsystems

WHAT DESIGN PATTERNS DO SOLVE ON THE OTHER HAND ARE COMMUNICATION BETWEEN OBJECTS AND CLASSES THAT ARE CUSTOMIZED TO SOLVE A GENERAL DESIGN PROBLEM IN A PARTICULAR CONTEXT

  • It names, abstracts, and identifies the key aspects of a common design structure that makes it useful for creating a reusable object-oriented design

The first design pattern we are going to discuss is the strategy Pattern

Defination - STRATEGY

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

THE STRATEGY PATTERN COMES UNDER THE CLASS OF BEHAVIORAL PATTERN - Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.

Also know as Policy

Many algorithms exist for breaking a stream of text into lines

How to identify Strategy patterns:

  1. there are multiple algorithms that will be needed at different times we do not want to support multiple algorithms using line breaking/conditionals
  2. it is difficult to accommodate change when implemented using line breaks and conditionals

When to use Strategy pattern:

  1. many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.
  2. you need different variants of an algorithm
  3. an algorithm uses data that clients should not know about
  4. a class defines such behavior and these appear as multiple conditional statements in an operations

Different actors in strategy:

  • Strategy declares an interface common to all supported algorithms. Context uses the interface to call the algorithm defined by a ConcreteStrategy
  • ConcreteStrategy implementation of the algorithm using the Strategy interface
  • Context maintains a reference to the strategy object

Folder Structure

Refer to the following for the code:

Top comments (0)