File tree 1 file changed +70
-0
lines changed 1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*:
2
+ 🍪 Template
3
+ -----------
4
+
5
+ The Template Pattern is used when two or more implementations of an
6
+ algorithm exist. The template is defined and then built upon with further
7
+ variations. Use this method when most (or all) subclasses need to implement
8
+ the same behavior. Traditionally, this would be accomplished with abstract
9
+ classes (as in Java). However in Swift, because abstract classes don't yet
10
+ exist, we need to accomplish the behavior using interface delegation.
11
+
12
+
13
+ ### Example
14
+ */
15
+
16
+ protocol ICodeGenerator {
17
+ func crossCompile( )
18
+ }
19
+
20
+ protocol IGeneratorPhases {
21
+ func collectSource( )
22
+ func crossCompile( )
23
+ }
24
+
25
+ class CodeGenerator : ICodeGenerator {
26
+ var delegate : IGeneratorPhases
27
+
28
+ init ( delegate: IGeneratorPhases ) {
29
+ self . delegate = delegate
30
+ }
31
+
32
+
33
+ //Template method
34
+ final func crossCompile( ) {
35
+ delegate. collectSource ( )
36
+ delegate. crossCompile ( )
37
+ }
38
+ }
39
+
40
+ class HTMLGeneratorPhases : IGeneratorPhases {
41
+ func collectSource( ) {
42
+ print ( " HTMLGeneratorPhases collectSource() executed " )
43
+ }
44
+
45
+ func crossCompile( ) {
46
+ print ( " HTMLGeneratorPhases crossCompile() executed " )
47
+ }
48
+ }
49
+
50
+ class JSONGeneratorPhases : IGeneratorPhases {
51
+ func collectSource( ) {
52
+ print ( " JSONGeneratorPhases collectSource() executed " )
53
+ }
54
+
55
+ func crossCompile( ) {
56
+ print ( " JSONGeneratorPhases crossCompile() executed " )
57
+ }
58
+ }
59
+
60
+
61
+
62
+ /*:
63
+ ### Usage
64
+ */
65
+
66
+ let htmlGen : ICodeGenerator = CodeGenerator ( delegate: HTMLGeneratorPhases ( ) )
67
+ let jsonGen : ICodeGenerator = CodeGenerator ( delegate: JSONGeneratorPhases ( ) )
68
+
69
+ htmlGen. crossCompile ( )
70
+ jsonGen. crossCompile ( )
You can’t perform that action at this time.
0 commit comments