-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStrategy.php
71 lines (60 loc) · 1.22 KB
/
Strategy.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
/**
* Created by PhpStorm.
* User: haobin
* Date: 2017/10/9
* Time: 23:23
*/
/**
*
* 策略模式
*/
interface IStrategy{
function filter($record);
}
class FindAfterStrategy implements IStrategy{
private $_name;
public function __construct($name)
{
$this->_name = $name;
}
public function filter($record)
{
return strcmp($this->_name, $record) <= 0;
}
}
class RandomStrategy implements IStrategy{
public function filter($record)
{
return rand(0, 1) < 0.5;
}
}
class UserList{
private $_list = array();
public function __construct($names)
{
if($names != null){
foreach($names as $name){
$this->_list [] = $name;
}
}
}
public function add($name)
{
$this->_list [] = $name;
}
public function find($filter)
{
$recs = array();
foreach($this->_list as $user){
if($filter->filter($user))
$recs [] = $user;
}
return $recs;
}
}
$ul = new UserList(array("Andy", "Jack", "Lori", "Megan"));
$f1 = $ul->find(new FindAfterStrategy("J"));
print_r($f1);
$f2 = $ul->find(new RandomStrategy());
print_r($f2);