转自:https://github.com/domnikl/DesignPatternsPHP
1 class Context 2 { 3 private Comparator $comparator; 4 5 public function __construct(Comparator $comparator) 6 { 7 $this->comparator = $comparator; 8 } 9 10 public function executeStrategy(array $elements): array 11 { 12 uasort($elements, [$this->comparator, ‘compare‘]); 13 14 return $elements; 15 } 16 }
1 interface Comparator 2 { 3 public function compare($a, $b): int; 4 } 5 6 class DateComparator implements Comparator 7 { 8 public function compare($a, $b): int 9 { 10 $aDate = new DateTime($a[‘date‘]); 11 $bDate = new DateTime($b[‘date‘]); 12 13 return $aDate <=> $bDate; 14 } 15 } 16 17 class IdComparator implements Comparator 18 { 19 public function compare($a, $b): int 20 { 21 return $a[‘id‘] <=> $b[‘id‘]; 22 } 23 }
1 class StrategyTest extends TestCase 2 { 3 public function provideIntegers() 4 { 5 return [ 6 [ 7 [[‘id‘ => 2], [‘id‘ => 1], [‘id‘ => 3]], 8 [‘id‘ => 1], 9 ], 10 [ 11 [[‘id‘ => 3], [‘id‘ => 2], [‘id‘ => 1]], 12 [‘id‘ => 1], 13 ], 14 ]; 15 } 16 17 public function provideDates() 18 { 19 return [ 20 [ 21 [[‘date‘ => ‘2014-03-03‘], [‘date‘ => ‘2015-03-02‘], [‘date‘ => ‘2013-03-01‘]], 22 [‘date‘ => ‘2013-03-01‘], 23 ], 24 [ 25 [[‘date‘ => ‘2014-02-03‘], [‘date‘ => ‘2013-02-01‘], [‘date‘ => ‘2015-02-02‘]], 26 [‘date‘ => ‘2013-02-01‘], 27 ], 28 ]; 29 } 30 31 public function testIdComparator($collection, $expected) 32 { 33 $obj = new Context(new IdComparator()); 34 $elements = $obj->executeStrategy($collection); 35 36 $firstElement = array_shift($elements); 37 $this->assertSame($expected, $firstElement); 38 } 39 40 public function testDateComparator($collection, $expected) 41 { 42 $obj = new Context(new DateComparator()); 43 $elements = $obj->executeStrategy($collection); 44 45 $firstElement = array_shift($elements); 46 $this->assertSame($expected, $firstElement); 47 } 48 }
原文:https://www.cnblogs.com/ts65214/p/12968448.html