Chapter 7. Behavioral Patterns: Strategy, State, and Template Method

Behavioral patterns are concerned with algorithms and communication between them. The operations that make up a single algorithm might be split up between different classes, making a complex arrangement that is difficult to manage and maintain. The behavioral patterns capture ways of expressing the division of operations between classes and optimize how the communication should be handled. In this first chapter on behavioral patterns, we'll look at three simple but very useful patterns: the Strategy, State, and Template Methods.

Strategy Pattern

Role

The Strategy pattern involves removing an algorithm from its host class and putting it in a separate class. There may be different algorithms (strategies) that are applicable for a given problem. If the algorithms are all kept in the host, messy code with lots of conditional statements will result. The Strategy pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it. The algorithms can also be expressed independently of the data they are using.

Illustration

A classic illustration of the Strategy pattern is found in the choice of algorithms for sorting. There are many sorting algorithms, and although some, such as Quicksort, are generally very fast, there are situations when this would be a poor choice and another algorithm, such as Mergesort, would perform better. Even the linear sorts, such as Shellsort, ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.