# Decorator パターン # # Java言語で学ぶデザインパターンと同様の例題をRubyで記述した。 # # coded by Takehiro Kaga # class Display def getColumns end def getRows end def getRowText(row) end def show (1..getRows).each {|i| puts self.getRowText(i-1) } end end class StringDisplay < Display def initialize(string) @string = string end def getColumns @string.length end def getRows 1 end def getRowText(row) if row == 0 @string else "" end end end class Border < Display def initialize(display) @display = display end end class SideBorder < Border def initialize(display, ch) @display = display super(@display) @borderChar = ch end def getColumns 1 + @display.getColumns + 1 end def getRows @display.getRows end def getRowText(row) @borderChar + @display.getRowText(row) + @borderChar end end class FullBorder < Border def initialize(display) @display = display super(@display) end def getColumns 1 + @display.getColumns + 1 end def getRows 1 + @display.getRows + 1 end def getRowText(row) if (row==0) "+" + makeLine("-", @display.getColumns) + "+" elsif (row == @display.getRows + 1) "+" + makeLine("-", @display.getColumns) + "+" else "|" + @display.getRowText(row - 1) + "|" end end def makeLine(ch, count) @buffer ="" count.times do @buffer += ch end @buffer end end b1 = StringDisplay.new("Hello, World") b2 = SideBorder.new(b1, "#") b3 = FullBorder.new(b2) b1.show b2.show b3.show b4 = SideBorder.new( FullBorder.new( FullBorder.new( SideBorder.new( FullBorder.new( StringDisplay.new("こんにちは。") ), "*" ) ) ), "/" ) b4.show