Strategy pattern

Short description: Software design pattern

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives runtime instructions as to which in a family of algorithms to use.[1]

Strategy lets the algorithm vary independently from clients that use it.[2] Strategy is one of the patterns included in the influential book Design Patterns by Gamma et al.[3] 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, the first-class function, classes or class instances in object-oriented programming languages, or accessing the language implementation's internal storage of code via reflection.

## Contents

* 1 Structure
* 1.1 UML class and sequence diagram
* 1.2 Class diagram
* 2 Strategy and open–closed principle
* 3 See also
* 4 References
* 5 External links

## Structure

### UML class and sequence diagram

A sample UML class and sequence diagram for the Strategy design pattern.[4]

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 Pattern in UML

[5]

Strategy pattern in LePUS3 (legend)

## Strategy and open–closed principle

Accelerate and brake behaviors must be declared in each new car model.

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:

Brake* brakeBehavior = new Brake();

package org.wikipedia.examples;

/* Encapsulated family of Algorithms
* Interface and its implementations

interface IBrakeBehavior {
public void brake();

class BrakeWithABS implements IBrakeBehavior {
public void brake() {
System.out.println("Brake with ABS applied");

class Brake implements IBrakeBehavior {
public void brake() {
System.out.println("Simple Brake applied");

// Client that can use the algorithms above interchangeably
abstract class Car {
private IBrakeBehavior brakeBehavior;

public Car(IBrakeBehavior brakeBehavior) {
this.brakeBehavior = brakeBehavior;

public void applyBrake() {
brakeBehavior.brake();

public void setBrakeBehavior(IBrakeBehavior brakeType) {
this.brakeBehavior = brakeType;

// Client 1 uses one algorithm (Brake) in the constructor
class Sedan extends Car {
public Sedan() {
super(new Brake());

// Client 2 uses another algorithm (BrakeWithABS) in the constructor
class SUV extends Car {
public SUV() {
super(new BrakeWithABS());

// Using the Car example
public class CarExample {
public static void main(String[] arguments) {
Car sedanCar = new Sedan();
sedanCar.applyBrake(); // This will invoke class "Brake"

Car suvCar = new SUV();
suvCar.applyBrake(); // This will invoke class "BrakeWithABS"

// set brake behavior dynamically
suvCar.setBrakeBehavior(new Brake());
suvCar.applyBrake(); // This will invoke class "Brake"

## See also

* Dependency injection
* Higher-order function
* List of object-oriented programming terms
* Mixin
* Policy-based design
* Type class
* Entity–component–system
* Composition over inheritance

## References

1. ↑ "The Strategy design pattern - Problem, Solution, and Applicability". http://w3sdesign.com/?gr=b09&ugr=proble.
2. ↑ Eric Freeman, Elisabeth Freeman, Kathy Sierra and Bert Bates, Head First Design Patterns, First Edition, Chapter 1, Page 24, O'Reilly Media, Inc, 2004. ISBN 978-0-596-00712-6
3. ↑ Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 315ff. ISBN 0-201-63361-2. https://archive.org/details/designpatternsel00gamm/page/315.
4. ↑ "The Strategy design pattern - Structure and Collaboration". http://w3sdesign.com/?gr=b09&ugr=struct.
5. ↑ "Design Patterns Quick Reference – McDonaldLand". http://www.mcdonaldland.info/2007/11/28/40/.

## External links

| The Wikibook Computer Science Design Patterns has a page on the topic of: Strategy implementations in various languages

|

* Strategy Pattern in UML Script error: The function "in_lang" does not exist.
* Geary, David (2002-04-26). "Strategy for success". JavaWorld. https://www.infoworld.com/article/2074195/strategy-for-success.html.
* Strategy Pattern for C article
* Refactoring: Replace Type Code with State/Strategy
* Implementation of the Strategy pattern in JavaScript

* v
* t
* e

Software design patterns

Creational|

* Abstract factory
* Builder
* Dependency injection
* Factory method
* Lazy initialization
* Multiton
* Object pool
* Prototype
* RAII
* Singleton

Structural|

* Adapter
* Bridge
* Composite
* Decorator
* Delegation
* Facade
* Flyweight
* Front controller
* Marker interface
* Module
* Proxy
* Twin

Behavioral|

* Blackboard
* Chain of responsibility
* Command
* Interpreter
* Iterator
* Mediator
* Memento
* Null object
* Observer
* Servant
* Specification
* State
* Strategy
* Template method
* Visitor

Functional|

* Closure
* Currying
* Function composition
* Functor
* Monad
* Generator

Concurrency|

* Active object
* Actor
* Balking
* Barrier
* Binding properties
* Coroutine
* Compute kernel
* Double-checked locking
* Event-based asynchronous
* Fiber
* Futex
* Futures and promises
* Guarded suspension
* Immutable object
* Join
* Lock
* Messaging
* Monitor
* Nuclear
* Proactor
* Reactor
* Read write lock
* Scheduler
* Thread pool
* Thread-local storage

Architectural|

* ADR
* Active record
* Broker
* Client–server
* CBD
* DAO
* DTO
* DDD
* ECB
* ECS
* EDA
* Front controller
* Identity map
* Interceptor
* Implicit invocation
* Inversion of control
* Model 2
* MOM
* Microservices
* MVA
* MVC
* MVP
* MVVM
* Monolithic
* Multitier
* Naked objects
* ORB
* P2P
* Publish–subscribe
* PAC
* REST
* SOA
* Service locator
* SN
* SBA
* Specification

Cloud
Distributed|

* Ambassador
* Anti-Corruption Layer
* Bulkhead
* Cache-Aside
* Circuit Breaker
* CQRS
* Compensating Transaction
* Competing Consumers
* Compute Resource Consolidation
* Event Sourcing
* External Configuration Store
* Federated Identity
* Gatekeeper
* Index Table
* Leader Election
* MapReduce
* Materialized View
* Pipes
* Filters
* Priority Queue
* Publisher-Subscriber
* Queue-Based Load Leveling
* Retry
* Scheduler Agent Supervisor
* Sharding
* Sidecar
* Strangler
* Throttling
* Valet Key

Other|

* Business delegate
* Composite entity
* Intercepting filter
* Lazy loading
* Mangler
* Mock object
* Type tunnel
* Method chaining

Books|

* Design Patterns
* Enterprise Integration Patterns

People|

* Christopher Alexander
* Erich Gamma
* Ralph Johnson
* John Vlissides
* Grady Booch
* Kent Beck
* Ward Cunningham
* Martin Fowler
* Robert Martin
* Jim Coplien
* Douglas Schmidt
* Linda Rising

Communities|

* The Hillside Group
* The Portland Pattern Repository

0.00

(0 votes)

Original source: https://en.wikipedia.org/wiki/Strategy pattern. Read more

|

Retrieved from "https://handwiki.org/wiki/index.php?title=Strategy_pattern&oldid=4158222"
*[v]: View this template
*[t]: Discuss this template
*[e]: Edit this template