What is Strategy pattern?
💻 coding

What is Strategy pattern?

1 min read 247 words
1 min read
ShareWhatsAppPost on X
  • 1The strategy pattern allows selecting an algorithm at runtime, enhancing flexibility in software design.
  • 2It enables algorithms to vary independently from the clients that utilize them, promoting code reusability.
  • 3The pattern encapsulates validation algorithms separately, allowing them to be reused across different validating objects without duplication.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The strategy pattern allows selecting an algorithm at runtime, enhancing flexibility in software design."

What is Strategy pattern?

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioural software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which is a family of algorithms to use.

Strategy lets the algorithm vary independently from clients that use it. A strategy is one of the patterns included in the influential book Design Patterns by Gamma et al. that popularized the concept of using design patterns to describe how to design flexible and reusable object-oriented software. Deferring the decision about which algorithm to use until runtime allows the calling code to be more flexible and reusable.

For instance, a class that performs validation on incoming data may use the strategy pattern to select a validation algorithm depending on the type of data, the source of the data, user choice, or other discriminating factors. These factors are not known until run-time and may require radically different validation to be performed. The validation algorithms (strategies), encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.

Typically the strategy pattern stores a reference to some code in a data structure and retrieves it. This can be achieved by mechanisms such as the native function pointer, the first-class function, classes or class instances in object-oriented programming languages, or accessing the language implementation's internal storage of code via reflection.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 1 August 2018 · 1 min read · 247 words

Part of AskGif Blog · coding

You might also like