Strategy pattern

From Wikipedia, the free encyclopedia

Jump to: navigation, search
Strategy Pattern in UML
Strategy pattern in LePUS3 (legend)

In computer programming, the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime.

In some programming languages, such as those without polymorphism, the issues addressed by this pattern are handled through forms of reflection, such as the native function pointer or function delegate syntax.

This pattern is invisible in languages with first-class functions. See the Python code for an example.

The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.

Contents

[edit] Code Examples

[edit] C++

#include <iostream>
 
using namespace std;
 
class StrategyInterface
{
    public:
        virtual void execute() = 0;
};
 
class ConcreteStrategyA: public StrategyInterface
{
    public:
        virtual void execute()
        {
            cout << "Called ConcreteStrategyA execute method" << endl;
        }
};
 
class ConcreteStrategyB: public StrategyInterface
{
    public:
        virtual void execute()
        {
            cout << "Called ConcreteStrategyB execute method" << endl;
        }
};
 
class ConcreteStrategyC: public StrategyInterface
{
    public:
        virtual void execute()
        {
            cout << "Called ConcreteStrategyC execute method" << endl;
        }
};
 
class Context
{
    private:
        StrategyInterface *_strategy;
 
    public:
        Context(StrategyInterface *strategy):_strategy(strategy)
        {
        }
 
        void set_strategy(StrategyInterface *strategy)
        {
            _strategy = strategy;
        }
 
        void execute()
        {
            _strategy->execute();
        }
};
 
int main(int argc, char *argv[])
{
    ConcreteStrategyA concreteStrategyA;
    ConcreteStrategyB concreteStrategyB;
    ConcreteStrategyC concreteStrategyC;
 
    Context contextA(&concreteStrategyA);
    Context contextB(&concreteStrategyB);
    Context contextC(&concreteStrategyC);
 
    contextA.execute();
    contextB.execute();
    contextC.execute();
 
    contextA.set_strategy(&concreteStrategyB);
    contextA.execute();
    contextA.set_strategy(&concreteStrategyC);
    contextA.execute();
 
    return 0;
}

[edit] Java

//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.execute(3,4);
 
        context = new Context(new ConcreteStrategySubtract());
        int resultB = context.execute(3,4);
 
        context = new Context(new ConcreteStrategyMultiply());
        int resultC = context.execute(3,4);
 
    }
 
}
 
// 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 ConcreteStrategyA'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 ConcreteStrategyB'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 ConcreteStrategyC's execute()");
        return a  * b;   // Do a multiply with a and b
    }
 
}
 
// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
 
    Strategy strategy;
 
    // Constructor
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }
 
    public int execute(int a, int b) {
        return this.strategy.execute(a, b);
    }
 
}

[edit] Python

Python has first-class functions, so there's no need to implement this pattern explicitly. However one loses information because the interface of the strategy is not made explicit. Here's an example you might encounter in GUI programming, using a callback function:

class Button:
    """A very basic button widget."""
    def __init__(self, submit_func, label):
        self.on_submit = submit_func   # Set the strategy function directly
        self.label = label
 
# Create two instances with different strategies
button1 = Button(sum, "Add 'em")
button2 = Button(lambda nums: " ".join(map(str, nums)), "Join 'em")
 
# Test each button
numbers = range(1, 10)   # A list of numbers 1 through 9
print button1.on_submit(numbers)   # displays "45"
print button2.on_submit(numbers)   # displays "1 2 3 4 5 6 7 8 9"

[edit] C

A struct in C can be used to define a class, and the strategy can be set using a function pointer. The following mirrors the Python example, and uses C99 features:

#include <stdio.h>
 
void print_sum(int n, int *array) {
  int total = 0;
  for (int i=0; i<n; i++) total += array[i];
  printf("%d", total);
}
 
void print_array(int n, int *array) {
  for (int i=0; i<n; i++) printf("%d ", array[i]);
}
 
int main(void) {
  typedef struct {
    void (*submit_func)(int n, int *array);
    char *label;
  } Button;
 
  // Create two instances with different strategies
  Button button1 = {print_sum, "Add 'em"};
  Button button2 = {print_array, "List 'em"};
 
  int n = 10, numbers[n];
  for (int i=0; i<n; i++) numbers[i] = i;
 
  button1.submit_func(n, numbers);
  button2.submit_func(n, numbers);
 
  return 0;
}

[edit] C# 3.0

In C# 3.0, with lambda expressions we can do something similar to the Python example above.

using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
  static void Main(string[] args)
  {
    var button1 = new MyButton((x) => x.Sum().ToString(), "Add them");
    var button2 = new MyButton((x) => string.Join(" ", x.Select(y => y.ToString()).ToArray()), "Join them");
 
    var numbers = Enumerable.Range(1, 10);
    Console.WriteLine(button1.Submit(numbers));
    Console.WriteLine(button2.Submit(numbers));
 
    Console.ReadLine();
  }
 
  public class MyButton
  {
    private readonly Func<IEnumerable<int>, string> submitFunction;
    public string Label { get; private set; }
 
    public MyButton(Func<IEnumerable<int>, string> submitFunction, string label)
    {
        this.submitFunction = submitFunction;
        Label = label;
    }
 
    public string Submit(IEnumerable<int> data)
    {
        return submitFunction(data);
    }
  }
}

[edit] C#

using System;
 
namespace Wikipedia.Patterns.Strategy
{
  // MainApp test application
  class MainApp
  {
    static void Main()
    {
      Context anObject;
 
      // Three contexts following different strategies
      anObject= new Context(new ConcreteStrategyA());
      anObject.Execute();
 
      anObject.UpdateContext(new ConcreteStrategyB());
      anObject.Execute();
 
      anObject.UpdateContext(new ConcreteStrategyC());
      anObject.Execute();
 
    }
  }
 
  // The classes that implement a concrete strategy must implement this Execute function.
  // The context class uses this to call the concrete strategy
  interface IStrategy
  {
    void Execute();
  }
 
  // Implements the algorithm using the strategy interface
  class ConcreteStrategyA : IStrategy
  {
    public void Execute()
    {
      Console.WriteLine( "Called ConcreteStrategyA.Execute()" );
    }
  }
 
  class ConcreteStrategyB : IStrategy
  {
    public void Execute()
    {
      Console.WriteLine( "Called ConcreteStrategyB.Execute()" );
    }
  }
 
  class ConcreteStrategyC : IStrategy
  {
    public void Execute()
    {
      Console.WriteLine( "Called ConcreteStrategyC.Execute()" );
    }
  }
 
  // Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
  class Context
  {
    IStrategy strategy;
 
    // Constructor
    public Context(IStrategy strategy)
    {
      this.strategy = strategy;
    }
 
    public void UpdateContext(IStrategy strategy)
    {
      this.strategy = strategy;
    }
 
    public void Execute()
    {
      strategy.Execute();
    }
  }
}

[edit] ActionScript 3

//invoked from application.initialize
private function init() : void
{
    var context:Context;
 
    context = new Context( new ConcreteStrategyA() );
    context.execute();
 
    context = new Context( new ConcreteStrategyB() );
    context.execute();
 
    context = new Context( new ConcreteStrategyC() );
    context.execute();
}
 
package org.wikipedia.patterns.strategy
{
    public interface IStrategy
    {
	function execute() : void ;
    }
}
 
package org.wikipedia.patterns.strategy
{
    public final class ConcreteStrategyA implements IStrategy
    {
	public function execute():void
	{
	     trace( "ConcreteStrategyA.execute(); invoked" );
	}
    }
}
 
package org.wikipedia.patterns.strategy
{
    public final class ConcreteStrategyB implements IStrategy
    {
	public function execute():void
	{
	     trace( "ConcreteStrategyB.execute(); invoked" );
	}
    }
}
 
package org.wikipedia.patterns.strategy
{
    public final class ConcreteStrategyC implements IStrategy
    {
	public function execute():void
	{
	     trace( "ConcreteStrategyC.execute(); invoked" );
	}
    }
}
 
package org.wikipedia.patterns.strategy
{
   public class Context
   {
	private var strategy:IStrategy;
 
	public function Context(strategy:IStrategy)
	{
	     this.strategy = strategy;
	}
 
	public function execute() : void
	{  
             strategy.execute();
	}
    }
}

[edit] PHP

<?php
class StrategyExample {
    public function __construct() {
        $context = new Context(new ConcreteStrategyA());
        $context->execute();
 
        $context = new Context(new ConcreteStrategyB());
        $context->execute();
 
        $context = new Context(new ConcreteStrategyC());
        $context->execute();
    }
}
 
interface IStrategy {
    public function execute();
}
 
class ConcreteStrategyA implements IStrategy {
    public function execute() {
        echo "Called ConcreteStrategyA execute method\n";
    }
}
 
class ConcreteStrategyB implements IStrategy {
    public function execute() {
        echo "Called ConcreteStrategyB execute method\n";
    }
}
 
class ConcreteStrategyC implements IStrategy {
    public function execute() {
        echo "Called ConcreteStrategyC execute method\n";
    }
}
 
class Context {
    private $strategy;
 
    public function __construct(IStrategy $strategy) {
        $this->strategy = $strategy;
    }
 
    public function execute() {
        $this->strategy->execute();
    }
}
 
new StrategyExample();
?>

[edit] Perl

Perl has first-class functions, so it doesn't require this pattern coded explicitly:

sort { lc($a) cmp lc($b) } @items

The strategy pattern can be formally implemented with Moose:

package Strategy;
use Moose::Role;
requires 'execute';
 
 
package FirstStrategy;
use Moose;
with 'Strategy';
 
sub execute {
    print "Called FirstStrategy->execute()\n";
}
 
 
package SecondStrategy;
use Moose;
with 'Strategy';
 
sub execute {
    print "Called SecondStrategy->execute()\n";
}
 
 
package ThirdStrategy;
use Moose;
with 'Strategy';
 
sub execute {
    print "Called ThirdStrategy->execute()\n";
}
 
 
package Context;
use Moose;
 
has 'strategy' => (
    is => 'rw',
    does => 'Strategy',
    handles => [ 'execute' ],  # automatic delegation
);
 
 
package StrategyExample;
use Moose;
 
# Moose's constructor
sub BUILD {
    my $context;
 
    $context = Context->new(strategy => 'FirstStrategy');
    $context->execute;
 
    $context = Context->new(strategy => 'SecondStrategy');
    $context->execute;
 
    $context = Context->new(strategy => 'ThirdStrategy');
    $context->execute;
}
 
 
package main;
 
StrategyExample->new;

[edit] Strategy versus Bridge

The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. 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.

[edit] Strategy Pattern and Open Closed Principle

According to 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 behaviors of 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. This may not be a concern when there are only a small number of models, but 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 (OCP) that states classes should be open for extension but closed for modification.

[edit] See also

[edit] External links

Personal tools