Design Patterns in Ruby [Digest 3] Strategy

本文介绍了一种设计模式——策略模式,该模式使用组合而非继承来实现算法的动态切换。通过实例展示了如何利用策略模式简化报告生成过程,并讨论了上下文与策略间的数据共享问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Template method is build around inheritance, the inheritance has the nature born relationship.

So the Strategy give a delegate solution.

 

So we use the strategy implementation:

 

 

class Formatter
	def output_report( title, text )
	raise 'Abstract method called'
	end
end

class HTMLFormatter < Formatter
	def output_report( title, text )
		puts('<html>')
		puts(' <head>')
		puts(" <title>#{title}</title>")
		puts(' </head>')
		puts(' <body>')
		text.each do |line|
			puts(" <p>#{line}</p>" )
		end
		puts(' </body>')
		puts('</html>')
	end
end

class PlainTextFormatter < Formatter
	def output_report(title, text)
		puts("***** #{title} *****")
		text.each do |line|
		puts(line)
		end
	end
end

 

So the Report is much simpler:

 

 

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( @title, @text )
	end
end

 

Usage is as below:

 

report = Report.new(HTMLFormatter.new)
report.output_report

 

The key idea of Strategy is to define a family of strategy objects those are used by the context class,

its use composition and delegation rather than inheritance, it is easy to switch strategies at runtime

 

 

there is a problem about sharing data between context and strategies,

the writer gives a example as below:

 

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(context)
		raise 'Abstract method called'
	end
end

class HTMLFormatter < Formatter
	def output_report(context)
		puts('<html>')
		puts(' <head>')
		puts(" <title>#{context.title}</title>")
		puts(' </head>')
		puts(' <body>')
		context.text.each do |line|
			puts(" <p>#{line}</p>")
		end
		puts(' </body>')
		puts('</html>')
	end
end

 

This technique simplifies the data flow but increases the coupling.

 

 

Then Ruby Duck Typing philosophy shows that we don't need the Formatter class any more. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值