5
2

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-07-12

概要

オブジェクト群の相互作用をカプセル化するオブジェクトを定義するパターン

以下の3種類のクラスからなる
1. Mediatorクラス(3.と通信するためのインターフェイスを定義)
2. Concrete Mediatorクラス(Colleagueオブジェクトを保持し、それらの協調的な振る舞いを実装する)
3. Colleagueクラス(1.のインターフェイスを介してのみ他のCollegueオブジェクトと通信する)

具体例と実装

学校で撮る空中写真を例にすると、

上記1~3はそれぞれ

  1. 配置指示クラス(Mediatorクラス。撮影者クラスが使うインターフェイスを定義)
  2. 撮影者クラス(Photographerクラス。男子生徒、女子生徒に指示を出す)
  3. 男子生徒クラス、女子生徒クラス(BoyGroup、GirlGroupクラス。撮影者の指示を受けて、動いたり、帽子の色を変えたり、ポーズを撮ったりする)

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

mediator.rb
class Mediator
  def change_cap_color
  end

  def change_direction
  end
end
photographer.rb
class Photographer < Mediator
  def initialize
  end

  def change_cap_color
    # 赤白帽の色を逆の色にする
  end

  def change_direction
    # 逆向きを向く
  end

  ....
end
boy_group.rb
class BoyGroup
  def initialize(photographer)
    @photographer = photographer
  end

  def change
    @photographer.change_cap_color
    @photographer.change_direction
  end

  def change_color
    @photographer.change_cap_color
  end
end
girl_group.rb
class GirlGroup
  def initialize(photographer)
    @photographer = photographer
  end

  def change
    @photographer.change_cap_color
    @photographer.change_direction
  end

  def change_color
    @photographer.change_cap_color
  end
end

メリット

  • Mediatorクラスをサブクラス化刷るだけで振る舞いを変更出来る
  • Collegueオブジェクトの結びつきを疎にし、再利用性を高める
  • 多対多の相互作用を一対多の関係に置き換える事ができる

まとめ

協調的な振る舞いを実装したい際に便利なパターン

5
2
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
5
2