8.2.1 Strategy Design pattern (the strategy style)
At run time, the policy pattern is useful if the application needs to choose between several algorithms, or between different parts of an algorithm. A common scenario is that when our application needs to perform several tasks, it is different only on very small sub-tasks. Using the policy mode, for the common part of the task, we just write once, plus parameterize, subtask (primitive operation) as its parameter value. Figure 8.1 shows the policy pattern in object-oriented notation.
Figure 8.1 Strategy is an interface that has a method for representing the original operation. Two specific policies for different operations, the Context class can choose between these implementations
To parameterize a task is to give it a subtask as a parameter value, potentially making the policy pattern look clearer in functional programming: It's just a higher-order function. The strategy interface in Figure 8.1 has only one method, which indicates that it is a simple function, and the two classes that implement it are valid concrete functions that can be created using a lambda function.
In a language that supports functions, we can replace the strategy interface with the appropriate function (the Func delegate in C # or the type of function in F #). Typically, we pass the policy directly to the operation method as a parameter value. Using the abstract name in Figure 8.1, we can write:
Context.operation (Arg => {
Implements the Specificstrategy
});
We have seen examples of this pattern when filtering the list. In this case, the function describing the condition is a specific strategy (we can write different filters using different strategies), the List.filter function or the Where method is quite an operation. This means that in languages that support higher-order functions, the policy pattern can be replaced at any time with higher-order functions.
The next pattern is somewhat similar, but in the behavior-centric application we discussed earlier, the list of processing behaviors is more relevant.
8.2.1 Strategy Design pattern (the strategy style)