LoginSignup
1
1

More than 5 years have passed since last update.

GoFのデザインパターン「state」をrubyで実装してみた

Last updated at Posted at 2018-05-14

Stateパターンとは、処理と状態を分離して書くことで、コードを簡潔にする手法のようなものです。

State役に状態に依存した振る舞いするメソッドを集め、Context役で現在の状態を持ちます。

以下がその簡単なサンプルコードです。

# State役
class State
end

# ConcreteState役
class DayState < State
  def do_use
    puts '昼間に金庫が使われました。'
  end

  def do_alarm
    puts '昼間に金庫のアラームがなりました。確認してください。'
  end
end

# ConcreteState役
class NightState < State
  def do_use
    puts '夜間に金庫が使われました。確認してください。'
  end

  def do_alarm
    puts '夜間に金庫のアラームがなりました。至急確認してください。'
  end
end

# Context役
class SafeFrame   # 金庫
  attr_reader :hour

  def initialize(hour)
    @hour = hour

    if hour < 9
      @state = NightState.new
    else
      @state = DayState.new
    end
  end

  def do_use
    @state.do_use
  end

  def do_alarm
    @state.do_alarm
  end
end


s = SafeFrame.new(10)
s.do_use
s.do_alarm

n = SafeFrame.new(8)
n.do_use
n.do_alarm

# 結果
# $ruby main.rb
# 昼間に金庫が使われました。
# 昼間に金庫のアラームがなりました。確認してください。
# 夜間に金庫が使われました。確認してください。
# 夜間に金庫のアラームがなりました。至急確認してください。
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