Jump to content

Strategy pattern

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Andy Dingley (talk | contribs) at 20:19, 5 May 2015 (Reverted 1 edit by 91.159.53.89 (talk): Rv self-promotional spam that doesn't offer anything to meet WP:EL. (TW)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected 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 patterns in software design.

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, 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 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.

Structure

Strategy Pattern in UML
Strategy pattern in LePUS3 (legend)

Example

C#

namespace IVSR.Designpattern.Strategy {
    //The interface for the strategies
    public interface ICalculateInterface {
       int Calculate(int value1, int value2);
    }

    //strategies
    //Strategy 1: Minus
    class Minus : ICalculateInterface {
        public int Calculate(int value1, int value2) {
            return value1 - value2;
        }
    }

    //Strategy 2: Plus
    class Plus : ICalculateInterface {
        public int Calculate(int value1, int value2) {
            return value1 + value2;
        }
    }

    //The client
    class CalculateClient {
        private ICalculateInterface calculateStrategy;

        //Constructor: assigns strategy to interface
        public CalculateClient(ICalculateInterface strategy) {
            this.calculateStrategy = strategy;
        }

        //Executes the strategy
        public int Calculate(int value1, int value2) {
            return calculateStrategy.Calculate(value1, value2);
        }
    }

    //Initialize
    protected void Page_Load(object sender, EventArgs e) {
        CalculateClient minusClient = new CalculateClient(new Minus());
        Response.Write("<br />Minus: " + minusClient.Calculate(7, 1).ToString());

        CalculateClient plusClient = new CalculateClient(new Plus());
        Response.Write("<br />Plus: " + plusClient.Calculate(7, 1).ToString());
    }
}

Java

The following example is in Java.

package javaapplication8;

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


 // Sample Strategy design pattern
public class JavaApplication8 {
    public static void main(String[] args){
        Customer a = new Customer();
        a.setStrategy(new NormalStrategy());
        
        // Normal billing
        a.add(1.2,1);
        
        // Start Happy Hour
        a.setStrategy(new HappyHourStrategy());
        a.add(1.2,2);
        
        // New Customer
        Customer b = new Customer();
        b.setStrategy(new HappyHourStrategy());
        b.add(0.8,1);
        // The Customer Pays
        a.printBill();

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

class Customer{
    private List<Double> drinks;
    private BillingStrategy strategy;

    public Customer() {
        this.drinks = new ArrayList<Double>();
    }

     // Add items to tab
    public void add(double price, int quantity){
        drinks.add(price*quantity);
    }

     // Payment of bill
    public void printBill(){
        System.out.println("Total due: " + strategy.sum(drinks));
        drinks.clear();
    }

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

}

interface BillingStrategy{
     // Return total price of drinks consumed
    public double sum(List<Double> drinks);
}

// Normal billing strategy (unchanged price)
class NormalStrategy implements BillingStrategy{
    public double sum(List<Double> drinks) {
        double sum = 0;
        for(Double i : drinks){
            sum += i;
        }
        return sum;
    }
}

 // Strategy for Happy hour (10% discount)
class HappyHourStrategy implements BillingStrategy{
    public double sum(List<Double> drinks) {
        double sum = 0;
        for(Double i : drinks){
            sum += i;
        }
        return sum*0.9;
    }
}

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

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. 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 which can use the algorithms above interchangeably */
public abstract class Car {
    protected IBrakeBehavior brakeBehavior;
    
    public void applyBrake() {
        brakeBehavior.brake();
    }

    public void setBrakeBehavior(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(String[] args) {
        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 also

References

  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