File tree Expand file tree Collapse file tree 2 files changed +122
-0
lines changed Expand file tree Collapse file tree 2 files changed +122
-0
lines changed Original file line number Diff line number Diff line change @@ -19,6 +19,7 @@ See details on http://maxsite.org/page/php-patterns
19
19
* "Decorator" (Structural)
20
20
* "Flyweight" (Structural)
21
21
* "Proxy" (Structural)
22
+ * "Template method" (Behavioral)
22
23
23
24
24
25
(c) MaxSite.org, 2019, http://maxsite.org/
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ /**
4
+ * Design pattern "Template method" (Behavioral)
5
+ * This is demo code
6
+ * See for details: http://maxsite.org/page/php-patterns
7
+ */
8
+
9
+ /**
10
+ * Base class
11
+ */
12
+ abstract class AlgorithmAbstract
13
+ {
14
+ // abstract methods
15
+ abstract function step1 ();
16
+ abstract function step2 ();
17
+
18
+ // method with implement
19
+ function baseOperation ()
20
+ {
21
+ echo 'AlgorithmAbstract baseOperation<br> ' ;
22
+ }
23
+
24
+ // free method
25
+ function hook () {}
26
+
27
+ // Run all Actions — this is algorithm
28
+ function run ()
29
+ {
30
+ $ this ->step1 ();
31
+ $ this ->step2 ();
32
+ $ this ->baseOperation ();
33
+ $ this ->hook ();
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Class1 for sample
39
+ */
40
+ class Class1 extends AlgorithmAbstract
41
+ {
42
+ function step1 ()
43
+ {
44
+ echo 'Class1 step1<br> ' ;
45
+ }
46
+
47
+ function step2 ()
48
+ {
49
+ echo 'Class1 step2<br> ' ;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Class2 for sample
55
+ */
56
+ class Class2 extends AlgorithmAbstract
57
+ {
58
+ function step1 ()
59
+ {
60
+ echo 'Class2 step1<br> ' ;
61
+ }
62
+
63
+ function step2 ()
64
+ {
65
+ echo 'Class2 step2<br> ' ;
66
+ }
67
+
68
+ function hook ()
69
+ {
70
+ echo 'Class2 hook<br> ' ;
71
+ }
72
+
73
+ function baseOperation ()
74
+ {
75
+ echo 'Class2 baseOperation<br> ' ;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Class3 for sample
81
+ */
82
+ class Class3 extends Class2
83
+ {
84
+ // replace method in Class2
85
+ function step2 ()
86
+ {
87
+ echo 'Class3 step2<br> ' ;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * demo
93
+ */
94
+
95
+ $ a = new Class1 ();
96
+ $ a ->run ();
97
+ /*
98
+ Class1 step1
99
+ Class1 step2
100
+ AlgorithmAbstract baseOperation
101
+ */
102
+
103
+ $ b = new Class2 ();
104
+ $ b ->run ();
105
+ /*
106
+ Class2 step1
107
+ Class2 step2
108
+ Class2 baseOperation
109
+ Class2 hook
110
+ */
111
+
112
+ $ c = new Class3 ();
113
+ $ c ->run ();
114
+ /*
115
+ Class2 step1
116
+ Class3 step2
117
+ Class2 baseOperation
118
+ Class2 hook
119
+ */
120
+
121
+ # end of file
You can’t perform that action at this time.
0 commit comments