# Flyweight パターン # # Java言語で学ぶデザインパターンと同様の例題をRubyで記述した。 # # coded by Takehiro Kaga # class BigChar def initialize(charname) buf = "" @charname = charname file = open("../tk/" + "big" + charname + ".txt") while line = file.gets buf += line buf += "\n" end file.close @fontdata = buf end def printchar print @fontdata end end # test1 # bigC1 = BigChar.new("1") # bigC1.printchar # puts " " # bigC3 = BigChar.new("3") # bigC3.printchar # puts " " class BigCharFactory # Singleton パターン適用 private_class_method :new @@singleObject = nil def BigCharFactory.create @@singleObject = new unless @@singleObject # 唯一のインスタンスを得る @@singleObject end def initialize @pool = Hash.new end def getBigChar(charname) bc = @pool[charname] if bc == nil bc = BigChar.new(charname) @pool[charname] = bc end bc end end # test2 # bcf = BigCharFactory.create # bc5 = bcf.getBigChar("5") # bc5.printchar class BigString def initialize(string) @bigchars = Array.new factory = BigCharFactory.create ary = string.split(//) ary.each { |char| @bigchars.push(factory.getBigChar( char.to_s )) } end def printchar @bigchars.each {|ch| ch.printchar } end end # ---- Main ---- # bs = BigString.new("1234") bs.printchar #--------プログラムはここまで----------------- # ここからそれぞれbig0.txtなど、ファイルとして格納すること #big0.txt ....######...... ..##......##.... ..##......##.... ..##......##.... ..##......##.... ..##......##.... ....######...... ................ #big1.txt ......##........ ..######........ ......##........ ......##........ ......##........ ......##........ ..##########.... ................ #big2.txt ....######...... ..##......##.... ..........##.... ......####...... ....##.......... ..##............ ..##########.... ................ #big3.txt ....######...... ..##......##.... ..........##.... ......####...... ..........##.... ..##......##.... ....######...... ................ #big4.txt ........##...... ......####...... ....##..##...... ..##....##...... ..##########.... ........##...... ......######.... ................ #big5.txt ..##########.... ..##............ ..##............ ..########...... ..........##.... ..##......##.... ....######...... ................ #big6.txt ....######...... ..##......##.... ..##............ ..########...... ..##......##.... ..##......##.... ....######...... ................ #big7.txt ..##########.... ..##......##.... ..........##.... ........##...... ......##........ ......##........ ......##........ ................ #big8.txt ....######...... ..##......##.... ..##......##.... ....######...... ..##......##.... ..##......##.... ....######...... ................ #big9.txt ....######...... ..##......##.... ..##......##.... ....########.... ..........##.... ..##......##.... ....######...... ................ #big-.txt ................ ................ ................ ................ ..##########.... ................ ................ ................