-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy_patern.rb
68 lines (57 loc) · 1.69 KB
/
strategy_patern.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
=begin
Рассмотрим еще один поведенческий шаблон проектирования,
который назвается Стратегия. Суть паттерна заключается в делегировании
какого-то поведения соответсвующему классу, реализующему определенный
алгоритм. Например, у нас есть какой-то отчет, и в зависимости от запроса
надо будет выводить информацию в HTML или XML, или как простой текст.
=end
class Report
attr_reader :title, :text
attr_accessor :formatter
def initialize(formatter)
@title = 'Monthly Report'
@text = ['Things are going', 'really, really well.']
@formatter = formatter
end
def output_report
@formatter.output_report(self)
end
end
class Formatter
def output_report(title, text)
raise 'Abstract method called'
end
end
class HTMLFormater < Formatter
def output_report(context)
p('<html>')
p('div')
p("#{context.title}")
context.text.each do |line|
p("#{line}")
end
p('/div')
p('</html>')
end
end
class XmlFormater < Formatter
def output_report(context)
p('<xml>')
p("#{context.title}")
p("#{context.text.join(' ')}")
end
end
class TextFormater < Formatter
def output_report(context)
p("**** #{context.title} ****")
context.text.each do |line|
p(line)
end
end
end
report = Report.new(HTMLFormater.new)
report.output_report
report.formatter = XmlFormater.new
report.output_report
report.formatter = TextFormater.new
report.output_report