- vừa được xem lúc

Blog#141: The Strategy Design Pattern In Javascript

0 0 9

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

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.

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 499

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 136

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 117

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 93

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 229