+7

The Strategy Design Pattern In Javascript

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.

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí