Strategy pattern
Encyclopedia
In computer programming
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...

, the strategy pattern (also known as the policy pattern) is a particular software design pattern
Design pattern (computer science)
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that...

, whereby algorithm
Algorithm
In mathematics and computer science, an algorithm is an effective method expressed as a finite list of well-defined instructions for calculating a function. Algorithms are used for calculation, data processing, and automated reasoning...

s can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithm
Algorithm
In mathematics and computer science, an algorithm is an effective method expressed as a finite list of well-defined instructions for calculating a function. Algorithms are used for calculation, data processing, and automated reasoning...

s, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

For instance, a class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, and/or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed. The validation 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.

The essential requirement in the programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

 is the ability to store a reference to some code in a data structure and retrieve it. This can be achieved by mechanisms such as the native function pointer, the first-class function
First-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning...

, classes or class instances in object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

 languages, or accessing the language implementation's internal storage of code via reflection
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....

.

Structure

Example

The following example is in Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

.

// The classes that implement a concrete strategy should implement this

// The context class uses this to call the concrete strategy
interface Strategy {
int execute(int a, int b);
}

// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {

public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyAdd's execute");
return a + b; // Do an addition with a and b
}
}

class ConcreteStrategySubtract implements Strategy {

public int execute(int a, int b) {
System.out.println("Called ConcreteStrategySubtract's execute");
return a - b; // Do a subtraction with a and b
}
}

class ConcreteStrategyMultiply implements Strategy {

public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyMultiply's execute");
return a * b; // Do a multiplication with a and b
}
}

// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {

private Strategy strategy;

// Constructor
public Context(Strategy strategy) {
this.strategy = strategy;
}

public int executeStrategy(int a, int b) {
return strategy.execute(a, b);
}
}

//StrategyExample test application

class StrategyExample {

public static void main(String[] args) {

Context context;

// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd);
int resultA = context.executeStrategy(3,4);

context = new Context(new ConcreteStrategySubtract);
int resultB = context.executeStrategy(3,4);

context = new Context(new ConcreteStrategyMultiply);
int resultC = context.executeStrategy(3,4);
}
}

Strategy versus Bridge

The UML
Unified Modeling Language
Unified Modeling Language is a standardized general-purpose modeling language in the field of object-oriented software engineering. The standard is managed, and was created, by the Object Management Group...

 class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern
Bridge pattern
The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently"...

. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.

The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

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. 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. Specific classes encapsulate 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 run-time 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;


This gives greater flexibility in design and is in harmony with the Open/closed principle
Open/closed principle
In object-oriented programming, the open/closed principle states "software entities should be open for extension, but closed for modification";...

 (OCP) that states that classes should be open for extension but closed for modification.

See also

  • Higher-order function
    Higher-order function
    In mathematics and computer science, higher-order functions, functional forms, or functionals are functions which do at least one of the following:*take one or more functions as an input*output a function...

  • Mixin
    Mixin
    In object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited or just reused by a subclass, while not meant for instantiation , Mixins are synonymous functionally with abstract base classes...

  • Policy-based design
    Policy-based design
    Policy-based design, also known as policy-based class design or policy-based programming, is a computer programming paradigm based on an idiom for C++ known as policies. It has been described as a compile-time variant of the strategy pattern, and has connections with C++ template metaprogramming...

  • List of object-oriented programming terms

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK