定義一系列的策略類,它們獨立封裝,而且遵循統一的接口設計模式
// 抽象排序策略接口 interface SortStrategy { public function sort($arr); } // 具體策略類-冒泡排序 class BubbleStrategy implements SortStrategy { public function sort($arr) { $len = count($arr); for ($i = 0; $i < $len - 1 ; $i++) { $flag = true; for ($j = 0; $j < $len - 1 - $i; $j++) { if ($arr[$j] > $arr[$j+1]) { list($arr[$j], $arr[$j+1]) = array($arr[$j+1], $arr[$j]); $flag = false; } } if ($flag) { break; } } return $arr; } } // 具體策略類-選擇排序 class SelectStrategy implements SortStrategy { public function sort($arr) { $len = count($arr); for ($i = 0; $i < $len - 1; $i++) { $minIndex = $i; for ($j = $i + 1; $j < $len; $j++) { if ($arr[$j] < $arr[$minIndex]) { $minIndex = $j; } } if ($minIndex != $i) { list($arr[$i], $arr[$minIndex]) = array($arr[$minIndex], $arr[$i]); } } return $arr; } } // 具體策略類-插入排序 class InsertStrategy implements SortStrategy { public function sort($arr) { $len = count($arr); for ($i = 1; $i < $len; $i++) { $preIndex = $i - 1; $nowVal = $arr[$i]; while ($preIndex >= 0 && $arr[$preIndex] > $nowVal) { $arr[$preIndex+1] = $arr[$preIndex]; $preIndex--; } $arr[++$preIndex] = $nowVal; } return $arr; } } // 具體策略類-歸併排序 class MergeStrategy implements SortStrategy { public function sort($arr) { $len = count($arr); if ($len < 2) { return $arr; } $mid = floor($len / 2); $left = array_slice($arr, 0, $mid); $right = array_slice($arr, $mid); return $this->merge($this->sort($left), $this->sort($right)); } private function merge($left, $right) { $res = []; while (count($left) > 0 && count($right) > 0) { if ($left[0] <= $right[0]) { $res[] = array_shift($left); } else { $res[] = array_shift($right); } } while (count($left) > 0) { $res[] = array_shift($left); } while (count($right) > 0) { $res[] = array_shift($right); } return $res; } } // 具體策略類-快速排序 class QuickStrategy implements SortStrategy { public function sort($arr) { $len = count($arr); if ($len < 2) { return $arr; } $mid = $arr[0]; $left = []; $right = []; for ($i = 1; $i < $len; $i++) { if ($arr[$i] > $mid) { $right[] = $arr[$i]; } else { $left[] = $arr[$i]; } } $left = $this->sort($left); $right = $this->sort($right); return array_merge($left, [$mid], $right); } }
用來管理策略,實現不一樣策略的切換功能ui
// 環境角色類 class Role { private $sortStrategy; public function __construct(SortStrategy $sortStrategy) { $this->sortStrategy = $sortStrategy; } public function asc($array) { return $this->sortStrategy->sort($array); } }
經過給予不一樣的具體策略,獲取結果this
// 客戶端代碼 $arr = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; $role = new Role(new MergeStrategy()); $data = $role->asc($arr); $role = new Role(new QuickStrategy()); $data = $role->asc($arr);