Strategy (policy)

Strategy pattern, also known as policy, defines a family or set of algorithms, encapsulates each one, and make them interchangeable. Strategy lets the algorithm vary independently of the clients that use it. When a group of classes differs only on their behavior, it is better to isolate the algorithms in separate classes and provide the ability to choose different algorithms at runtime.

The preceding diagram shows the strategy structure, and implementation of sorting algorithms (as a family) and depends on the input depends on the volume for sort, then the client can use the intended algorithm from the Concrete strategy sorting classes.

The benefits are as listed:

  • Enables open and closed principle
  • Enables large-scale reusability
  • Eliminates conditional statements (leads to clean code, well-defined responsibilities, easy to test, and so on)

Impacts are as follows:

  • Clients need to be aware of different strategies and how they differ
  • Communication overhead between strategy and context
  • Increased number of objects
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset