Open main menu

Wikipedia β

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. The strategy pattern

  • defines a family of algorithms,
  • encapsulates each algorithm, and
  • makes the algorithms interchangeable within that family.

Strategy lets the algorithm vary independently from clients that use it.[1] 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.

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 run-time 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.

The essential requirement to implement the Strategy pattern 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, classes or class instances in object-oriented programming languages, or accessing the language implementation's internal storage of code via reflection.



The Strategy [2] design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

What problems can the Strategy design pattern solve? [3]

  • A class should be configured with an algorithm instead of implementing an algorithm directly.
  • An algorithm should be selected and exchanged at run-time.

What is an algorithm? An algorithm is usually defined as a procedure that takes some value as input, performs a finite number of steps, and produces some value as output.
From a more general point of view, an algorithm is a piece of code that does something appropriate.

Implementing an algorithm directly within the class that uses the algorithm is inflexible because it commits the class to a particular algorithm at compile-time and makes it impossible to change the algorithm later independently from (without having to change) the class. This also stops the class from being reusable when another algorithm should be used.

What solution does the Strategy design pattern describe?

  • Define a separate (strategy) object that encapsulates an algorithm. That is, define an interface (Strategy) for performing an algorithm, and define classes that implement the interface (algorithm) in different ways.
  • A class delegates an algorithm to a strategy object at run-time instead of implementing an algorithm directly (that is, instead of committing to an algorithm at compile-time).

This makes a class independent of a particular algorithm (how an algorithm is implemented).
A class can be configured with a strategy object, which is used to perform an algorithm. Moreover, the strategy object can be exchanged at run-time.

See also the UML class and sequence diagram below.


UML class and sequence diagramEdit

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

In the above UML class diagram, the Context class doesn't 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 run-time 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 diagramEdit

Strategy Pattern in UML
Strategy pattern in LePUS3 (legend)



The following example is in C#.

 1 public class StrategyPatternWiki
 2 {
 3     public static void Main(String[] args)
 4     {
 5         Customer firstCustomer = new Customer(new NormalStrategy());
 7         // Normal billing
 8         firstCustomer.Add(1.0, 1);
10         // Start Happy Hour
11         firstCustomer.Strategy = new HappyHourStrategy();
12         firstCustomer.Add(1.0, 2);
14         // New Customer
15         Customer secondCustomer = new Customer(new HappyHourStrategy());
16         secondCustomer.Add(0.8, 1);
17         // The Customer pays
18         firstCustomer.PrintBill();
20         // End Happy Hour
21         secondCustomer.Strategy = new NormalStrategy();
22         secondCustomer.Add(1.3, 2);
23         secondCustomer.Add(2.5, 1);
24         secondCustomer.PrintBill();
25     }
26 }
29 class Customer
30 {
31     private IList<double> drinks;
33     // Get/Set Strategy
34     public IBillingStrategy Strategy { get; set; }
36     public Customer(IBillingStrategy strategy)
37     {
38         this.drinks = new List<double>();
39         this.Strategy = strategy;
40     }
42     public void Add(double price, int quantity)
43     {
44         drinks.Add(Strategy.GetActPrice(price * quantity));
45     }
47     // Payment of bill
48     public void PrintBill()
49     {
50         double sum = 0;
51         foreach (double i in drinks)
52         {
53             sum += i;
54         }
55         Console.WriteLine("Total due: " + sum);
56         drinks.Clear();
57     }
58 }
60 interface IBillingStrategy
61 {
62     double GetActPrice(double rawPrice);
63 }
65 // Normal billing strategy (unchanged price)
66 class NormalStrategy : IBillingStrategy
67 {
68     public double GetActPrice(double rawPrice)
69     {
70         return rawPrice;
71     }
73 }
75 // Strategy for Happy hour (50% discount)
76 class HappyHourStrategy : IBillingStrategy
77 {
79     public double GetActPrice(double rawPrice)
80     {
81         return rawPrice * 0.5;
82     }
83 }


The following example is in Java.

import java.util.ArrayList;
import java.util.List;

public class StrategyPatternWiki {

    public static void main(final String[] arguments) {
        Customer firstCustomer = new Customer(new NormalStrategy());

        // Normal billing
        firstCustomer.add(1.0, 1);

        // Start Happy Hour
        firstCustomer.setStrategy(new HappyHourStrategy());
        firstCustomer.add(1.0, 2);

        // New Customer
        Customer secondCustomer = new Customer(new HappyHourStrategy());
        secondCustomer.add(0.8, 1);
        // The Customer pays

        // End Happy Hour
        secondCustomer.setStrategy(new NormalStrategy());
        secondCustomer.add(1.3, 2);
        secondCustomer.add(2.5, 1);

class Customer {

    private List<Double> drinks;
    private BillingStrategy strategy;

    public Customer(final BillingStrategy strategy) {
        this.drinks = new ArrayList<Double>();
        this.strategy = strategy;

    public void add(final double price, final int quantity) {

    // Payment of bill
    public void printBill() {
        double sum = 0;
        for (Double i : drinks) {
            sum += i;
        System.out.println("Total due: " + sum);

    // Set Strategy
    public void setStrategy(final BillingStrategy strategy) {
        this.strategy = strategy;


interface BillingStrategy {
    double getActPrice(final double rawPrice);

// Normal billing strategy (unchanged price)
class NormalStrategy implements BillingStrategy {

    public double getActPrice(final double rawPrice) {
        return rawPrice;


// Strategy for Happy hour (50% discount)
class HappyHourStrategy implements BillingStrategy {

    public double getActPrice(final double rawPrice) {
        return rawPrice*0.5;


A much simpler example in "modern Java" (Java 8 and later), using lambdas, may be found here.

Strategy and open/closed principleEdit

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. 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 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();
/* Encapsulated family of Algorithms
 * Interface and its implementations
public interface IBrakeBehavior {
    public void brake();

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

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

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

    public void applyBrake() {

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

/* Client 1 uses one algorithm (Brake) in the constructor */
public class Sedan extends Car {
    public Sedan() {
        this.brakeBehavior = new Brake();

/* Client 2 uses another algorithm (BrakeWithABS) in the constructor */
public class SUV extends Car {
    public SUV() {
        this.brakeBehavior = new BrakeWithABS();

/* Using the Car example */
public class CarExample {
    public static void main(final 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"

This gives greater flexibility in design and is in harmony with the Open/closed principle (OCP) that states that classes should be open for extension but closed for modification.

See alsoEdit


  1. ^ 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
  2. ^ 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. 
  3. ^ "The Strategy design pattern - Problem, Solution, and Applicability". Retrieved 2017-08-12. 
  4. ^ "The Strategy design pattern - Structure and Collaboration". Retrieved 2017-08-12. 

External linksEdit