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