-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTemplateMethodExt.php
96 lines (81 loc) · 1.89 KB
/
TemplateMethodExt.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
namespace DesignPatterns\Behavioral;
/**
* Abstract class which defines the template method convert() and declares all its steps
*/
abstract class AbstractFileConverter
{
/**
* Template method
*/
final public function convert()
{
$this->beforeSteps();
$this->openFile();
$this->validate();
$this->makeConversion();
$this->closeFile();
$this->afterSteps();
}
/**
* Default implementations of some steps
*/
protected function openFile()
{
echo "Step1. Read from file..\n";
}
protected function closeFile()
{
echo "Step4. Close file descriptor..\n";
}
/**
* These steps have to be implemented in subclasses
*/
abstract protected function validate();
abstract protected function makeConversion();
/**
* Optional methods provide additional extension points
*/
protected function beforeSteps()
{
}
protected function afterSteps()
{
}
}
/**
* Concrete class implements all abstract operations of the abstract class.
* They also overrides some operations with a default implementation
*/
class PDFFileConverter extends AbstractFileConverter
{
protected function validate()
{
echo "Step2. Validate PDF file..\n";
}
protected function makeConversion()
{
echo "Step3. Convert PDF file..\n";
}
}
/**
* Another concrete class with self implementation of some steps
*/
class CSVFileConverter extends AbstractFileConverter
{
protected function validate()
{
echo "Step2. Validate CSV file..\n";
}
protected function makeConversion()
{
echo "Step3. Convert CSV file..\n";
}
}
# Client code example
(new PDFFileConverter())->convert();
/* Output:
Step1. Read from file..
Step2. Validate PDF file..
Step3. Convert PDF file..
Step4. Close a file descriptor.. */