vendredi 13 avril 2012

Design pattern strategy

Définition

Le design pattern strategy définit une famille d'algorithmes, encapsule chacun d'eux, et les rend interchangeables. Il laisse l’algorithme changer indépendamment des clients qui les utilisent.

Diagramme UML

Diagramme de classes du design pattern strategy

Exemple en PHP

// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface Strategy
{
    public function execute($a, $b);
}

// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy
{
    public function execute($a, $b)
    {
       echo 'Called ConcreteStrategyAdd\'s execute()' . "\n";
       return $a + $b;  // Do an addition with a and b
    }
}

class ConcreteStrategySubtract implements Strategy
{
    public function execute($a, $b)
    {
       echo 'Called ConcreteStrategySubtract\'s execute()' . "\n";
       return $a - $b;  // Do a subtraction with a and b
    }
}

class ConcreteStrategyMultiply implements Strategy
{
    public function execute($a, $b)
    {
       echo 'Called ConcreteStrategyMultiply\'s execute()' . "\n";
       return $a * $b;   // Do a multiplication with a and b
    }    
}

// Configured with a ConcreteStrategy object and maintains a reference 
// to a Strategy object
class Context
{
    private $strategy;

    public function __construct(Strategy $strategy)
    {
        $this->setStrategy($strategy);
    }

    public function executeStrategy($a, $b)
    {
        return $this->strategy->execute($a, $b);
    }

    public function setStrategy(Strategy $strategy)
    {
        $this->strategy = $strategy;
    }
}

// Three contexts following different strategies
$context = new Context(new ConcreteStrategyAdd());
echo $context->executeStrategy(3, 4) . "\n";

$context->setStrategy(new ConcreteStrategySubtract());
echo $context->executeStrategy(3, 4) . "\n";

$context->setStrategy(new ConcreteStrategyMultiply());
echo $context->executeStrategy(3, 4) . "\n";
L'exemple affiche :
Called ConcreteStrategyAdd's execute()
7
Called ConcreteStrategySubtract's execute()
-1
Called ConcreteStrategyMultiply's execute()
12

Aucun commentaire:

Enregistrer un commentaire