Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # State
- module State
- def do_use(context)
- raise NotImplementedError.new("#{self.class}##{__method__} が実装されていません")
- end
- def do_alarm(context)
- raise NotImplementedError.new("#{self.class}##{__method__} が実装されていません")
- end
- def do_phone(context)
- raise NotImplementedError.new("#{self.class}##{__method__} が実装されていません")
- end
- end
- # Context
- module Context
- def record_log(message)
- raise NotImplementedError.new("#{self.class}##{__method__} が実装されていません")
- end
- def call_security_center(message)
- raise NotImplementedError.new("#{self.class}##{__method__} が実装されていません")
- end
- end
- # ConcreteState
- class DayState
- include State
- @singleton = self.new
- class << self
- def get_instance
- @singleton
- end
- end
- def do_use(context)
- context.record_log('金庫使用(昼間)')
- end
- def do_alarm(context)
- context.call_security_center('非常ベル(昼間)')
- end
- def do_phone(context)
- context.call_security_center('通話(昼間)')
- end
- end
- # ConcreteState
- class NightState
- include State
- @singleton = self.new
- class << self
- def get_instance
- @singleton
- end
- end
- def do_use(context)
- context.call_security_center('非常ベル(夜間)')
- end
- def do_alarm(context)
- context.call_security_center('非常ベル(夜間)')
- end
- def do_phone(context)
- context.call_security_center('通話(夜間)')
- end
- end
- # ConcreteContext
- class SafeguardSystem
- include Context
- def initialize(hour)
- @state = change_state(hour)
- end
- def set_clock(hour)
- change_state(hour)
- end
- def switch_use
- @state.do_use(self)
- end
- def switch_alarm
- @state.do_alarm(self)
- end
- def switch_phone
- @state.do_phone(self)
- end
- # mediator pattern
- def change_state(hour)
- if hour >= 9 && hour < 17
- @state = DayState.get_instance
- else
- @state = NightState.get_instance
- end
- end
- def record_log(message)
- puts "record_log: #{message}"
- end
- def call_security_center(message)
- puts "call_security_center: #{message}"
- end
- end
- # main
- safeguard_system = SafeguardSystem.new(0)
- 24.times do |hour|
- safeguard_system.set_clock(hour)
- safeguard_system.switch_use
- safeguard_system.switch_alarm
- safeguard_system.switch_phone
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement