-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02-builder.rb
101 lines (79 loc) · 1.92 KB
/
02-builder.rb
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
97
98
99
100
# 02. BUILDER PATTERN
# director
class TextPrinter
def initialize(opts)
@formatter = opts.fetch(:formatter)
end
def print(text)
header = text[0]
body = text[1]
footer = text[2]
@formatter.build_header(header)
@formatter.build_body(body)
@formatter.build_footer(footer)
puts @formatter.getFormattedText()
end
end
# builder
class Formatter
def build_header(header)
raise NotImplementedError
end
def build_body(body)
raise NotImplementedError
end
def build_footer(footer)
raise NotImplementedError
end
def getFormattedText
raise NotImplementedError
end
end
# concrete builder
class HTMLFormatter < Formatter
def build_header(header)
@header = "<h1>#{ header }</h1>"
end
def build_body(body)
@body = "<p>#{ body }</p>"
end
def build_footer(footer)
@footer = "<small>#{ footer }</small>"
end
def getFormattedText
[@header, @body, @footer].join("\n")
end
end
# concrete builder
class MarkdownFormatter < Formatter
def build_header(header)
@header = "##{ header }"
end
def build_body(body)
@body = body
end
def build_footer(footer)
@footer = "*#{ footer }*"
end
def getFormattedText
[@header, @body, @footer].join("\n")
end
end
# client
header = 'Builder Pattern'
body = <<-eos
The builder pattern is an object creation software design pattern.
Unlike the abstract factory pattern and the factory method pattern whose
intention is to enable polymorphism, the intention of the builder pattern
is to find a solution to the telescoping constructor anti-pattern
eos
footer = '©2015 wadus'
text = [header, body, footer]
# Print using the HTMLFormatter
html_formatter = HTMLFormatter.new
console = TextPrinter.new(formatter: html_formatter)
console.print(text)
# Print using the MarkdownFormatter
markdown_formatter = MarkdownFormatter.new
console = TextPrinter.new(formatter: markdown_formatter)
console.print(text)