Blog#141: The Strategy Design Pattern In Javascript

image.png

The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.


Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

Have you ever found yourself in a situation where you have a similar task that needs to be accomplished, but the approach to solving it is different each time? That's where the strategy design pattern comes in handy.

What is the strategy design pattern?

The strategy design pattern is a design pattern that enables selecting an algorithm at runtime. It lets you change the behavior of an object based on the context it is used in. The strategy design pattern consists of creating objects which represent various strategies, and a context object whose behavior changes as per its strategy object. The strategy object changes the executing algorithm of the context object.

Why use the strategy design pattern?

  • It lets you change the behavior of an object at runtime
  • It lets you substitute algorithms easily
  • You can add new strategies or algorithms easily, without affecting existing clients
  • It provides a simple way to switch between algorithms
  • It helps to reduce conditional complexity in the code

How to use the strategy design pattern?

  1. Define a common interface for all the strategies.
  2. Create concrete strategy classes that implement the common interface.
  3. Create a context class that contains a reference to the strategy object.
  4. Pass the strategy object to the context class to configure its behavior.

Example

Here are some examples for the strategy design pattern in Javascript:

1. Sorting an array

// Sorting Strategies
class QuickSort {
  sort(arr) {
    console.log(`QuickSort: ${arr}`);
  }
}

class MergeSort {
  sort(arr) {
    console.log(`MergeSort: ${arr}`);
  }
}

class BubbleSort {
  sort(arr) {
    console.log(`BubbleSort: ${arr}`);
  }
}

// Sorting Context
class SortingContext {
  constructor(strategy) {
    this.strategy = strategy;
  }

  setStrategy(strategy) {
    this.strategy = strategy;
  }

  sort(arr) {
    this.strategy.sort(arr);
  }
}

// Usage
const quickSort = new QuickSort();
const mergeSort = new MergeSort();
const bubbleSort = new BubbleSort();

const context = new SortingContext();

context.setStrategy(quickSort);
context.sort([3, 2, 1]);

context.setStrategy(mergeSort);
context.sort([3, 2, 1]);

context.setStrategy(bubbleSort);
context.sort([3, 2, 1]);

// Result:
// QuickSort: 3,2,1
// MergeSort: 3,2,1
// BubbleSort: 3,2,1

2. Encrypting data

// Encryption Strategies
class AESEncryption {
  encrypt(data) {
    console.log(`AESEncryption: ${data}`);
  }
}

class DESEncryption {
  encrypt(data) {
    console.log(`DESEncryption: ${data}`);
  }
}

class RSAEncryption {
  encrypt(data) {
    console.log(`RSAEncryption: ${data}`);
  }
}

// Encryption Context
class EncryptionContext {
  constructor(strategy) {
    this.strategy = strategy;
  }
  setStrategy(strategy) {
    this.strategy = strategy;
  }

  encrypt(data) {
    this.strategy.encrypt(data);
  }
}

// Usage
const aesEncryption = new AESEncryption();
const desEncryption = new DESEncryption();
const rsaEncryption = new RSAEncryption();

const context = new EncryptionContext();

context.setStrategy(aesEncryption);
context.encrypt("secret data");

context.setStrategy(desEncryption);
context.encrypt("secret data");

context.setStrategy(rsaEncryption);
context.encrypt("secret data");

// Result:
// AESEncryption: secret data
// DESEncryption: secret data
// RSAEncryption: secret data

3. Compressing data

// Compression Strategies
class GzipCompression {
  compress(data) {
    console.log(`GzipCompression: ${data}`);
  }
}

class Bzip2Compression {
  compress(data) {
    console.log(`Bzip2Compression: ${data}`);
  }
}

class TarCompression {
  compress(data) {
    console.log(`TarCompression: ${data}`);
  }
}

// Compression Context
class CompressionContext {
  constructor(strategy) {
    this.strategy = strategy;
  }

  setStrategy(strategy) {
    this.strategy = strategy;
  }

  compress(data) {
    this.strategy.compress(data);
  }
}

// Usage
const gzipCompression = new GzipCompression();
const bzip2Compression = new Bzip2Compression();
const tarCompression = new TarCompression();

const context = new CompressionContext();

context.setStrategy(gzipCompression);
context.compress("large data");

context.setStrategy(bzip2Compression);
context.compress("large data");

context.setStrategy(tarCompression);
context.compress("large data");

// Result
// GzipCompression: large data
// Bzip2Compression: large data
// TarCompression: large data

Conclusion

The strategy design pattern is a powerful design pattern that lets you change the behavior of an object at runtime. It provides a simple way to switch between algorithms, reducing conditional complexity in the code. With the code samples provided above, you can see how the strategy design pattern can be applied to various use cases, such as sorting an array, encrypting data, and compressing data.

And Finally

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊


The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.

NGUYỄN ANH TUẤN

Xin chào, mình là Tuấn, một kỹ sư phần mềm đang làm việc tại Tokyo. Đây là blog cá nhân nơi mình chia sẻ kiến thức và kinh nghiệm trong quá trình phát triển bản thân. Hy vọng blog sẽ là nguồn cảm hứng và động lực cho các bạn. Hãy cùng mình học hỏi và trưởng thành mỗi ngày nhé!

Đăng nhận xét

Mới hơn Cũ hơn