Strategy Pattern

<?php
/* ~~~~~~~~~~~~~ Car Repair Classes ~~~~~~~~~~~~~ */

abstract class CarRepair{
protected $_duration,$_cost_calculator;
public function __construct($duration, CostCalculator $cost_calculator){
$this->_duration = $duration;
$this->_cost_calculator = $cost_calculator;
}
public function get_cost(){
return $this->_cost_calculator->get_cost($this);
}
public function get_charge_type(){
return $this->_cost_calculator->get_charge_type($this);
}
public function get_duration(){
return $this->_duration;
}
}

class OilChange extends CarRepair{
public function __construct($duration, CostCalculator $cost_calculator){
parent::__construct($duration,$cost_calculator);
}
//Overwrite Parent Method
public function get_cost(){
//For overwrite example only - calcs should be kept in the CostCalculator Classes
return $this->_cost_calculator->get_cost($this) * 2;
}
//Specific Method
public function get_job_type(){
return 'Oil Change';
}

}

class TireRotation extends CarRepair{
public function __construct($duration, CostCalculator $cost_calculator){
parent::__construct($duration,$cost_calculator);
}
//Specific Method
public function get_job_type(){
return 'Tire Rotation';
}
}

/* ~~~~~~~~~~~~~ Cost Calculators ~~~~~~~~~~~~~ */

abstract class CostCalculator{
abstract function get_cost(CarRepair $car_repair);
abstract function get_charge_type();
}

class HourlyCostCalculator extends CostCalculator{
public function get_cost(CarRepair $car_repair){
return($car_repair->get_duration() * 30);// $30 an hour
}
public function get_charge_type(){
return '$30 Hourly Rate';
}
}

class DiscountHourlyCostCalculator extends CostCalculator{
public function get_cost(CarRepair $car_repair){
return($car_repair->get_duration() * 20);// $20 an hour
}
public function get_charge_type(){
return '$20 Discount Hourly Rate';
}
}

//Print Example
echo '~~~~~~~~~~~~~ Strategy Example: ~~~~~~~~~~~~~';

$jobs[] = new OilChange(4, new HourlyCostCalculator());
$jobs[] = new TireRotation(4, new DiscountHourlyCostCalculator());

foreach($jobs as $job){
echo $job->get_job_type() . ':<br>';
echo 'Job Charge: $' . $job->get_cost() . '<br>';
echo 'Charge Type: ' . $job->get_charge_type() . '<br><br>';
}
?>

0 Comments

You must be logged in to post a comment.