Template mode is good, but it still has some flaws. For example, its implementation relies on inheritance and lacks sufficient flexibility. At this point we need to find a more optimal solution-the strategy model.
The following is the report template implemented using the policy mode
1 #Strategy 12 classHtmlformatter3 defoutput_report title, Text4Puts''5Puts''6Puts'<title>'+ title +'</title>'7Puts''8Puts'<body>'9Text.each do |line|TenPuts"<p>#{line}</p>" One End APuts'</body>' -Puts'' - End the End - - #Strategy 2 - classPlaintextformatter + defoutput_report title, Text -Puts'******** '+ title +' ********' +Text.each do |line| A puts line at End - End - End - - #Environment - classReporter in attr_reader:title,: Text - Attr_accessor:formater to + defInitialize Formater -@title ='My Report' the@text = ['This is my report',' the report','It is ok'] *@formater =Formater $ EndPanax Notoginseng - #you can refer to your own reference into the policy, which simplifies the flow of data, but increases the coupling between the environment and the policy the defOutput_report + @formater. Output_report @title, @text A #@formater. Output_report Self the End + - End $ $ reporter.new (htmlformatter.new). Output_report - reporter.new (plaintextformatter.new). Output_report - the #then come back and say Template method mode, - #Template method pattern is to look for common and then extract out templatesWuyi #The policy pattern is to encapsulate different methods into a single policy, which is not the same and it is difficult to extract the common parts the - #If the strategy is simple enough, there is only one method that can be passed through a code block Wu classProcreporter - attr_reader:title,: Text About Attr_accessor:formatter $ - defInitialize &Formatter -@title ='My Report' -@text = ['This is my report',' the report','It is ok'] A@formatter =Formatter + End the - #you can refer to your own reference into the policy, which simplifies the flow of data, but increases the coupling between the environment and the policy $ defOutput_report the @formatter. Call Self the End the the End - inreport_html = procreporter.new do |context| thePuts'' thePuts'' AboutPuts'<title>'+ Context.title +'</title>' thePuts'' thePuts'<body>' theContext.text.each do |line| +Puts"<p>#{line}</p>" - End thePuts'</body>'BayiPuts'' the End the P Report_html.output_report - - #A good example of a simple lightweight policy object theA = ['1',' A','123','6234567','3',' -'] the P A.sort theP A.sort {|a, b| a.length <=> B.length}
Design Patterns in ruby--strategy mode