LoginSignup
1
1

More than 5 years have passed since last update.

SimpleDelegator で Decolator パターンを実装する

Last updated at Posted at 2017-02-25

SimpleDelegator で Decolator パターンを実装します。
SimpleDelegator についてはるりまを参照ください。
Decolator パターンについてはWikipediaを参照ください。

サンプル

人間のフルネームを表示するプログラムを作ります。
フルネームを表示には以下のパターンがあります。

種類 表示
日本人 姓 名
日本人疑問形 姓 名?
日本人まとめ記事タイトル風 【fullname】姓 名
米国人 名 姓
米国人疑問形 名 姓?
米国人まとめ記事タイトル風 【fullname】名 姓

これを Decolator パターンで実装します。
(つっこみどころはきにしない)

コード

require 'delegate'

class Person
  attr_reader :first_name, :last_name

  def initialize(first_name, last_name)
    @first_name, @last_name = first_name, last_name
  end
end

class JapaneseDecorator < SimpleDelegator
  def fullname
    "#{last_name} #{first_name}"
  end
end

class AmericanDecorator < SimpleDelegator
  def fullname
    "#{first_name} #{last_name}"
  end
end

class QuestionDecorator < SimpleDelegator
  def fullname
    "#{super}?"
  end
end

class MatomeTitleDecorator < SimpleDelegator
  def fullname
    "【fullname】#{super}"
  end
end

person = Person.new('Joe', 'Hogashi')

puts person.first_name
puts person.last_name

puts AmericanDecorator.new(person).fullname
puts JapaneseDecorator.new(person).fullname
puts QuestionDecorator.new(AmericanDecorator.new(person)).fullname
puts QuestionDecorator.new(JapaneseDecorator.new(person)).fullname
puts MatomeTitleDecorator.new(AmericanDecorator.new(person)).fullname
puts MatomeTitleDecorator.new(JapaneseDecorator.new(person)).fullname
puts MatomeTitleDecorator.new(QuestionDecorator.new(AmericanDecorator.new(person))).fullname
puts MatomeTitleDecorator.new(QuestionDecorator.new(JapaneseDecorator.new(person))).fullname

実行結果

Joe
Hogashi
Joe Hogashi
Hogashi Joe
Joe Hogashi?
Hogashi Joe?
【fullname】Joe Hogashi
【fullname】Hogashi Joe
【fullname】Joe Hogashi?
【fullname】Hogashi Joe?
1
1
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
1