# Template パターン # # Java言語で学ぶデザインパターンと同様の例題をRubyで記述した。 # # coded by Takehiro Kaga # class AbstractDisplay # 抽象クラスAbstractDisplay def open # サブクラスに実装をまかせる抽象メソッド(1) open end def customPrint # サブクラスに実装をまかせる抽象メソッド(2) customPrint end def close # サブクラスに実装をまかせる抽象メソッド(3) close end def display # この抽象クラスで実装しているメソッドdisplay open # まずopenして・・・ for i in 1..5 # 5回printをくりかえして・・・ customPrint end close # 最後にcloseする。これがdisplayメソッドで実装されている内容 end end class CharDisplay < AbstractDisplay # AbstractDisplayを継承 def initialize(ch) @ch = ch end def open print("<") end def customPrint print(@ch) end def close puts(">") end end class StringDisplay < AbstractDisplay # AbstractDisplayを継承 def initialize(stringchr) @stringchr = stringchr end def open printLine end def customPrint puts ("|" + @stringchr + "|") end def close printLine end def printLine n = @stringchr.size print "+" for i in 1..n print "-" end puts "+" end end d1 = CharDisplay.new("H") d2 = StringDisplay.new("Hello, world.") d3 = StringDisplay.new("こんにちわ。") d1.display d2.display d3.display