Decoratorパターンについて

こんにちは!

今回はDecoratorパターンについてまとめます。

何をしたいか

  • 文字に装飾を付けたい
  • 色を付ける場合、太字にする場合、色を付けて太字にしたい場合などがある

コード

class Decorator
  def initialize(word)
    @word = word
  end

  def to_string
    @word.to_string
  end
end

class BoldDecorator < Decorator
  def to_string
    "\e[1m" + super + "\e[0m"
  end
end

class RedDecorator < Decorator
  def to_string
    "\e[31m" + super + "\e[0m"
  end
end

class BlueDecorator < Decorator
  def to_string
    "\e[34m" + super + "\e[0m"
  end
end
  • wordはto_stringで文字列を返すオブジェクトとする

使い方

decorated = BoldDecorator.new(word)
decorated = BlueDecorator.new(decorated)
puts decorated.to_string
  • 上の例だと太字かつ青文字が出力される

おわりに

デザインパターンはやりたいことに合致しているときは強力なツールになりますね。今回のケースも、最初はデコレーターパターンを使わずに実装していましたが、これはデコレーターパターンでは?と気づいて再実装してからは、コード量が減って可読性もあがりました!

19/100