LoginSignup
1
0

More than 5 years have passed since last update.

Ruby Compositeパターン

Posted at

はじめに

構造がきれいな設計のために、デザインパターンを再学習しています。
今回はCompositeパターンを扱います。

環境

Ruby 2.3.0

概要

構造に関するパターンのひとつです。
Compositeパターンは、木構造、階層構造、ツリー構造のオブジェクトを作りたいときに
上位のオブジェクトとか単一のオブジェクトかを考えさえせたくないときに利用できます。

例えば、ディレクトリ(上位オブジェクト)とファイル(単一オブジェクト)の構造の場合に、ディレクトリもファイルも同一視できます。

GoFいわく「全体が部分のように振る舞う」テクニックとのこと。
また、Compositeとは英語で「複合的」という意味です。

コード

Componentを継承して、ファイルとディレクトリを作成しています。

Strategy.rb
class Component
  attr_accessor :name
  def initialize(name)
    @name = name
  end
end

class FileComponent < Component
  def initialize(name)
    super(name)
  end
end

class DirectoryComponent < Component
  def initialize(name)
    super(name)
    @components = []
  end

  def add(component)
    @components << component
  end

  def remove(component)
    @components.delete(component)
  end

end

picture = DirectoryComponent.new("PICTURE")
picture.add(FileComponent.new("child.jpg"))
picture.add(FileComponent.new("car.jpg"))
picture.add(FileComponent.new("landscape.jpe"))

usb = DirectoryComponent.new("UsbDevice")
usb.add(picture)

参考

1
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
1
0