-
Notifications
You must be signed in to change notification settings - Fork 13
/
02_strategy_sample1.rb
56 lines (49 loc) · 1.25 KB
/
02_strategy_sample1.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
# レポートの出力を抽象化したクラス(抽象戦略)
class Formatter
def output_report(title, text)
raise 'Called abstract method !!'
end
end
# HTML形式に整形して出力(具体戦略)
class HTMLFormatter < Formatter
def output_report(report)
puts "<html><head><title>#{report.title}</title></head><body>"
report.text.each { |line| puts "<p>#{line}</p>" }
puts '</body></html>'
end
end
# PlaneText形式に整形して出力(具体戦略)
class PlaneTextFormatter < Formatter
def output_report(report)
puts "***** #{report.title} *****"
report.text.each { |line| puts(line) }
end
end
# レポートを表す(コンテキスト)
class ReportT
# Test
attr_reader :title, :text
attr_accessor :formatter
def initialize(formatter)
@title = 'report title'
@text = %w(text1 text2 text3)
@formatter = formatter
end
def output_report
@formatter.output_report(self)
end
end
# ===========================================
report = Report.new(HTMLFormatter.new)
report.output_report
#<html><head><title>report title</title></head><body>
#<p>text1</p>
#<p>text2</p>
#<p>text3</p>
#</body></html>
report.formatter = PlaneTextFormatter.new
report.output_report
#***** report title *****
#text1
#text2
#text3