💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 29.模板模式 在模板模式中,一个类提供了一个基础模板,其他类出于其预期目的使用了该基础模板。 让我们来看一个例子,看看下面显示的代码。 我们有一个名为`News`的类,可以通过各种机制(例如文本(例如 SMS),通过 HTML 格式的网络,使用 json 或使用 XML)来传递此新闻。 因此,`News`类实现了一个基本模板。 它具有称为`print`的方法,该方法可打印`header`,`body`和`footer`三种方法的输出。 也就是说,它定义了一个模板,该模板表示要传递新闻时,它必须具有标题,然后是新闻正文,然后是新闻页脚。 现在,键入并运行下面的程序 [template.rb](code/design_patterns/template.rb) 。 ```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 ```rb | ``` # template.rb class News attr_accessor :title, :content def initialize title, content @title = title @content = content end def header raise "Not Implemented" end def body raise "Not Implemented" end def footer raise "Not Implemented" end def print puts header puts body puts footer end end class PlainText &lt; News def header """ ************************* * TODAYS NEWS * ************************* """ end def footer """ ************************* * GOODBYE! * ************************* """ end def body """ #{title} ========================= #{content} """ end end PlainText.new( "Good Morning!", "Nice weather today" ).print ```rb | ``` 输出量 ```rb ************************* * TODAYS NEWS * ************************* Good Morning! ========================= Nice weather today ************************* * GOODBYE! * ************************* ``` 现在来看`PlainText`类,它继承自`News`,因此它必须实现`News`定义的模式。 因此(HTG3)要做的就是定义三种方法,即`header`,`body`和`footer`。 确实如此。 现在以纯文本格式打印新闻,我们需要做的就是初始化`PlainText`类的实例,并在其上调用`print`。 通过以下代码完成 ```rb PlainText.new( "Good Morning!", "Nice weather today" ).print ``` 因此,如果你看到的话,模板模式定义了基本模板或结构,从而为想要扩展它的类带来了清晰度和结构。 这也可以减少在派生类中需要完成的编码。 ### 29.1。 行使 为什么不修改模板模式代码,以便我们得到这样的 HTML 格式的文本 ```rb <html> <head> <title>Today's News</title> </head> <body> <h1>Good Morning!</h1> <p>Nice weather today</p> </body> </html> ```