Design Pattern: Strategy

Strategy is a way to encapsulate, manage and interchange (also at runtime) algorithms.

In the following example, we have three classes (A,B and C) that implement an interface with the method f().
The class AlgoContainer must be initiated by passing the object (external instantiation) or the class name (internal instantation).


Interface StrategyInt
{
public function f();
}

class A implements StrategyInt {
public function f() { print "A:f()"; }
}

class B implements StrategyInt {
public function f() { print "B:f()"; }
}

class C implements StrategyInt {
public function f() { print "C:f()"; }
}

class AlgoContainer {
private $strategy;
private $name;
public function __construct($s){
if (is_object($s))
$this->strategy = $s;
else
$this->strategy = new $s();
}
public function doF() {
$this->strategy->f();
}
}

//Usage 1 (external instantiation):
$ac = new AlgoContainer(new A);
$ac-> doF();

//Usage 2 (internal instantiation):
$ac = new AlgoContainer("A");
$ac-> doF();