Help us understand the problem. What is going on with this article?

Ruby Compositeパターン

More than 1 year has passed since last update.

はじめに

構造がきれいな設計のために、デザインパターンを再学習しています。
今回は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)

参考

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away