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

vendredi 6 avril 2012

Quick Launch a Linux instance on Amazon EC2

  1. Sign in to the AWS console at https://console.aws.amazon.com/ec2/
  2. Select a region (Ex: EU West)
  3. Click Launch Instance
  4. Select Quick Launch Wizard
  5. Type the name of your instance (Ex: Web Server)
  6. Create and download a new key pair (Ex: myhosts)
  7. Choose the configuration: Amazon Linux AMI 64 bits
  8. Click Continue and Launch