File tree Expand file tree Collapse file tree 2 files changed +74
-0
lines changed Expand file tree Collapse file tree 2 files changed +74
-0
lines changed Original file line number Diff line number Diff line change @@ -11,6 +11,7 @@ See details on http://maxsite.org/page/php-patterns
11
11
* "Registry" (Structural)
12
12
* "Composite" (Structural)
13
13
* "Builder" (Creational)
14
+ * "Strategy" (Behavioral)
14
15
15
16
16
17
(c) MaxSite.org, 2019, http://maxsite.org/
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ /**
4
+ * Design pattern "Strategy" (Behavioral)
5
+ * This is demo code
6
+ * See for details: http://maxsite.org/page/php-patterns
7
+ */
8
+
9
+ /**
10
+ * Methods of Strategy
11
+ */
12
+ interface Strategy
13
+ {
14
+ public function execute ();
15
+ }
16
+
17
+ /**
18
+ * Strategy A
19
+ */
20
+ class StrategyA implements Strategy
21
+ {
22
+ public function execute ()
23
+ {
24
+ echo 'StrategyA execute<br> ' ;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Strategy B
30
+ */
31
+ class StrategyB implements Strategy
32
+ {
33
+ public function execute ()
34
+ {
35
+ echo 'StrategyB execute<br> ' ;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Base Context
41
+ */
42
+ class Context
43
+ {
44
+ private $ strategy ;
45
+
46
+ public function __construct (Strategy $ strategy )
47
+ {
48
+ $ this ->strategy = $ strategy ;
49
+ }
50
+
51
+ public function execute ()
52
+ {
53
+ $ this ->strategy ->execute ();
54
+ }
55
+ }
56
+
57
+ /**
58
+ * demo
59
+ */
60
+
61
+ $ context = new Context (new StrategyA ()); // first strategy
62
+ $ context ->execute ();
63
+ /*
64
+ StrategyA execute
65
+ */
66
+
67
+ $ context = new Context (new StrategyB ()); // other strategy
68
+ $ context ->execute ();
69
+ /*
70
+ StrategyB execute
71
+ */
72
+
73
+ # end of file
You can’t perform that action at this time.
0 commit comments