首页 > 其他 > 详细

设计模式 策略模式

时间:2020-05-26 21:48:18      阅读:43      评论:0      收藏:0      [点我收藏+]

转自: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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!