Skip to content

Instantly share code, notes, and snippets.

@Bolinha1
Last active August 29, 2015 14:18
Show Gist options
  • Save Bolinha1/672575f321a745d4d4ae to your computer and use it in GitHub Desktop.
Save Bolinha1/672575f321a745d4d4ae to your computer and use it in GitHub Desktop.
Strategy pattern in PHP.
<?php
//strategy
interface Average
{
public function calculate(Values $values);
}
//concrete strategy
class AveragePondered implements Average
{
public function calculate(Values $values)
{
$value = $values->getValues();
$weight = $values->getWeight();
$multiplicationResult = 0;
$weightSumResult = array_sum($weight);
for($i = 0; $i < count($value) && $i < count($weight); $i++)
{
$multiplicationResult += $value[$i] * $weight[$i];
}
return $average = $multiplicationResult / $weightSumResult;
}
}
//concrete strategy
class AverageArithmetic implements Average
{
public function calculate(Values $values)
{
$elements = $values->getValues();
$elementsSum = array_sum($elements);
$totalElements = count($elements);
return $average = $elementsSum / $totalElements;
}
}
//context
abstract class Values
{
protected $value;
protected $average;
protected function __construct(Average $average)
{
$this->average = $average;
}
public function addValues($value)
{
$this->value[] = $value;
}
public function getValues()
{
return $this->value;
}
abstract public function getAverage();
}
class Pondered extends Values
{
private $weight;
public function __construct(Average $average)
{
parent::__construct($average);
}
public function addWeight($weight)
{
$this->weight[] = $weight;
}
public function getWeight()
{
return $this->weight;
}
public function getAverage()
{
return $this->average->calculate($this);
}
}
class Arithmetic extends Values
{
public function __construct(Average $average)
{
parent::__construct($average);
}
public function getAverage()
{
return $this->average->calculate($this);
}
}
//execution
$valuePondered = new Pondered(new AveragePondered());
$valuePondered->addValues(5);
$valuePondered->addWeight(2.2);
$valuePondered->addValues(8);
$valuePondered->addWeight(3.3);
$valuePondered->addValues(5);
$valuePondered->addWeight(4.4);
$valuePondered->addValues(4);
$valuePondered->addWeight(5.5);
var_dump("Pondered " .$valuePondered->getAverage());
$valueArithmetic = new Arithmetic(new AverageArithmetic());
$valueArithmetic->addValues(10);
$valueArithmetic->addValues(10);
$valueArithmetic->addValues(10);
$valueArithmetic->addValues(10);
var_dump("Arithmetic " .$valueArithmetic->getAverage());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment