LoginSignup
2
0

More than 5 years have passed since last update.

-【デザインパターン】 Flyweightパターン

Posted at

概要

多数の細かいオブジェクトを効率よくサポートするために共有を利用するパターン

以下の5種類のクラスからなる
1. Flyweightクラス(インスタンスを再利用するためのインターフェイスを定義)
2. Concrete Flyweightクラス(1.のインターフェイスを実装)
3. UnsharedConcreteFlyweightクラス(ConcreteFlyweightオブジェクトを子として管理する)
4. Flyweight Factoryクラス(flyweightを生成、管理する)
5. Clientクラス(flyweightへの参照を保持する)

具体例と実装

文書作成エディタを例にすると、

上記1~5はそれぞれ

  1. 文字イメージクラス(Glyphクラス。文字入力のためのインターフェイスを定義)
  2. 文字クラス(Characterクラス。文字入力のインターフェイスを実装)
  3. 今回はなし
  4. 文字ファクトリークラス(CharacterFactoryクラス。文字を生成)
  5. ユーザクラス(Userクラス、文書を作成する)

が対応する。
コードの詳細は以下

glyph.rb
class Glyph
  def draw
  end
end
character.rb
class Character < Glyph
  def initialize(character, font)
    @character = character
    @font = font
  end

  def draw
    # @character, @fontの元に文字を描画
  end
end
character_factory.rb
class CharacterFactory
  def initialize()
    @characters = Hash.new
  end

  def create_character(character, font)
    character = @characters[character][font]
    if character.nil?
      @characters[character][font] = Character.new(character, font)
    else
      character
    end
  end
end
user.rb
character_factory = CharacterFactory.new

character_factory.create_character('s', :utf8).draw
character_factory.create_character('u', :utf8).draw
character_factory.create_character('c', :utf8).draw
character_factory.create_character('c', :utf8).draw
character_factory.create_character('e', :utf8).draw
character_factory.create_character('s', :utf8).draw
character_factory.create_character('s', :utf8).draw

メリット

  • オブジェクトをflyweightとして共有することによってメモリが節約できる

まとめ

再利用できるインスタンスが存在し、プログラムを省リソース化したい際に利用するパターン

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0