Sunday 26 June 2016

Strategy Design Pattern

This pattern is used when we have several ways (algorithms) to perform the same operation and we want the application to pick the specific way based on the parameters you have. The point is to separate algorithms into classes that can be plugged in at run time.
In the below example, the function in the Sort class decides which object to create in order to carry out the sorting based on the size of the array which is passed in the constructor.
<?php
Class Sort {
public function __construct($data) {
$this->sort($data);
}
public function sort($data) {
if (count($data) > 5) {
$sortData = new QuickSort();
$sortData->sort($data);
} else {
$sortData = new MergeSort();
$sortData->sort($data);
}
}
}
Class QuickSort {
public function sort($data) {
echo "sorting the data using quicksort";
}
}
Class MergeSort {
public function sort($data) {
echo "sorting the data using mergesort";
}
}
$mySort = new Sort(array(1,3,2,3,2,3,2,3,3));
?>

No comments:

Post a Comment