LoginSignup
2
0

More than 5 years have passed since last update.

【デザインパターン】 Compositeパターン

Last updated at Posted at 2015-06-21

概要

木構造の再帰的なデータを表現するためのパターン

以下の4種類のクラスからなる
1. Componentクラス(枝と葉に共通するインターフェイス、親、子へのアクセスを宣言し、適宜実装する)
2. Leafクラス(階層構造の末端の葉オブジェクトを表し、振る舞いを定義する)
3. Compositeクラス(枝オブジェクトの振る舞いを定義し、1.で宣言された子オブジェクトに関するオペレーションを実装する)
4. Clientクラス(1.のインターフェイスを通して、枝や葉オブジェクトを操作する)

具体例と実装

ファイルとディレクトリからなる木構造を例にすると

上記1~4はそれぞれ
1. ディレクトリエントリークラス
2. ファイルクラス
3. ディレクトリクラス
4. クライアントクラス

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

directory_entry.rb
class DirectoryEntry
  def get_name
  end

  def remove
  end
end
file.rb
class File < DirectoryEntry
  def initialize(name)
    @name = name
  end

  def get_name
    @name
  end

  def remove
    # ファイルを削除
  end
end
directory.rb
class Directory < DirectoryEntry
  def initialize(name)
    @name = name
    @children = []
  end

  def get_name
    @name
  end

  def remove
    @children.each do |item|
      item.remove
    end
    # ディレクトリ自身を削除
  end

  def add(item)
    @children << item
  end
end

メリット

  • クライアントは、木構造内のすべてのオブジェクトを一様に扱うことが出来る
  • 新しく定義されたCompositeクラス、Leafクラスは既存の構造に自動的に取り込むことができる

まとめ

木構造を構成するオブジェクトを透過的に扱えるパターン。
循環のない再帰的な構造を表現する際に用いる。

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