In
computer programming
Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, the strategy pattern (also known as the policy pattern) is a
behavioral software design pattern
In software engineering, a software design pattern or design pattern is a general, reusable solution to a commonly occurring problem in many contexts in software design. A design pattern is not a rigid structure to be transplanted directly into s ...
that enables selecting an
algorithm
In mathematics and computer science, an algorithm () is a finite sequence of Rigour#Mathematics, mathematically rigorous instructions, typically used to solve a class of specific Computational problem, problems or to perform a computation. Algo ...
at runtime. Instead of implementing a single algorithm directly, code receives runtime instructions as to which in a family of algorithms to use.
Strategy lets the algorithm vary independently from clients that use it. 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 runtime 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 code in a data structure and retrieves it. This can be achieved by mechanisms such as the native
function pointer
A function pointer, also called a subroutine pointer or procedure pointer, is a pointer referencing executable code, rather than data. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments ...
, the
first-class function
In computer science, a programming language is said to have first-class functions if it treats function (programming), functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning ...
, classes or class instances in
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
languages, or accessing the language implementation's internal storage of code via
reflection.
Structure
UML class and sequence diagram
In the above
UML class diagram, the
Context
class does not implement an algorithm directly.
Instead,
Context
refers to the
Strategy
interface for performing an algorithm (
strategy.algorithm()
), which makes
Context
independent of how an algorithm is implemented.
The
Strategy1
and
Strategy2
classes implement the
Strategy
interface, that is, implement (encapsulate) an algorithm.
The
UML sequence diagram
shows the runtime interactions: The
Context
object delegates an algorithm to different
Strategy
objects. First,
Context
calls
algorithm()
on a
Strategy1
object,
which performs the algorithm and returns the result to
Context
.
Thereafter,
Context
changes its strategy and calls
algorithm()
on a
Strategy2
object,
which performs the algorithm and returns the result to
Context
.
Class diagram
Strategy and open/closed principle
According to the strategy pattern, the behaviors of a class should not be inherited. Instead, they should be encapsulated using interfaces. This is compatible with the
open/closed principle (OCP), which proposes that classes should be open for extension but closed for modification.
As an example, consider a car class. Two possible functionalities for car are ''brake'' and ''accelerate''. Since accelerate and brake behaviors change frequently between models, a common approach is to implement these behaviors in subclasses. This approach has significant drawbacks; accelerate and brake behaviors must be declared in each new car model. The work of managing these behaviors increases greatly as the number of models increases, and requires code to be duplicated across models. Additionally, it is not easy to determine the exact nature of the behavior for each model without investigating the code in each.
The strategy pattern uses
composition instead of inheritance. In the strategy pattern, behaviors are defined as separate interfaces and specific classes that implement these interfaces. This allows better decoupling between the behavior and the class that uses the behavior. The behavior can be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes. Behaviors can also be changed at runtime as well as at design-time. For instance, a car object's brake behavior can be changed from
BrakeWithABS()
to
Brake()
by changing the
brakeBehavior
member to:
brakeBehavior = new Brake();
/* Encapsulated family of Algorithms
* Interface and its implementations
*/
public interface IBrakeBehavior
public class BrakeWithABS implements IBrakeBehavior
public class Brake implements IBrakeBehavior
/* Client that can use the algorithms above interchangeably */
public abstract class Car
/* Client 1 uses one algorithm (Brake) in the constructor */
public class Sedan extends Car
/* Client 2 uses another algorithm (BrakeWithABS) in the constructor */
public class SUV extends Car
/* Using the Car example */
public class CarExample
See also
*
Dependency injection
*
Higher-order function In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following:
* takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself ...
*
List of object-oriented programming terms
*
Mixin
*
Policy-based design
*
Type class
*
Entity–component–system
*
Composition over inheritance
References
External links
Strategy Pattern in UML
*
Strategy Pattern for C article* Implementation of the Strategy pattern in JavaScript
{{Design Patterns Patterns
Software design patterns
Articles with example C Sharp code
Articles with example Java code