From: gotoken@... (GOTO Kentaro) Date: 1999-04-13T20:40:03+09:00 Subject: [ruby-list:13690] Flyweight (Re: Integer[num]) ごとけんです In message "[ruby-list:13677] Re: Integer[num] (Re: Ruby and LISP)" on 99/04/13, 中村暁史 writes: >->例えば、TeX のようなフォーマッタを作る場合に文字をそこそこ粒度の >->大きなオブジェクトにするならこうやってメモリを稼ぐ価値はあると > >フライウェイトパターン、でしたっけ? >あれは逆に、小さいけど多数うじゃうじゃ出てくる場合でも、 >参照で扱うことの優位性はある、とかいう話だったような。 ええと、「そこそこ粒度の大きなオブジェクト」というのはよくない 表現でした。Flyweight パターンは確かに「多数の細かいオブジェク トを効率よくサポートするために共有を利用する」ものですね。 # いま辞書索いたらFlyweightってフライ級のボクサーのコトだそうで -- gotoken # 蛇足:FlyweightFactory を実現する mix-in (よーするにハッシュ :-) # # flyweightfactory.rb # # class Foo # include FlyweghtFactory # end # Foo[arg] #=> an object which is unique for arg # Foo.new(arg) #=> Error # module FlyweightFactory def FlyweightFactory.append_features(mod) super mod.private_class_method :new mod.const_set("HASHTABLE", {}) def mod.[](key) self::HASHTABLE[key] || self::HASHTABLE[key] = new(key) end end end # End of library; An example starts here if __FILE__ == $0 class Alphabet include FlyweightFactory attr_reader :data def initialize(char) if !char.kind_of?(String) && char.size != 1 raise ArgumentError.new "one length string required `#{char.inspect}'" end @data = char[0] end end chartbl = [] while $_ = DATA.gets chartbl.push row = [] $_.split(//).each{|c| row.push Alphabet[c]} end print "# \"alphabet\"(object id) ... \n" chartbl.each do |row| print row.collect{|col| "#{col.data.chr.inspect}(#{col.id})" }.join(" "), "\n" end end __END__ John Smith Tom