Skip to content

Commit

Permalink
変更に追従する:Observer #75
Browse files Browse the repository at this point in the history
・5.2 通知を受けるよりよい方法

EFROR-62
  • Loading branch information
k2works committed Aug 18, 2017
1 parent b53ed10 commit d667e9e
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 21 deletions.
22 changes: 18 additions & 4 deletions app/domains/design_pattern/observer/employee.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,31 @@ class Employee
attr_reader :name
attr_accessor :title, :salary

def initialize(name, title, salary, payroll)
def initialize(name, title, salary)
@name = name
@title = title
@salary = salary
@payroll = payroll
@observers = []
end

def salary=(new_salary)
@salary = new_salary
@payroll.update(self)
notify_observers
end

def notify_observers
@observers.each do |observer|
observer.update(self)
end
end

def add_observer(observer)
@observers << observer
end

def delete_observer(observer)
@observers.delete(observer)
end
end
end
end
end
9 changes: 9 additions & 0 deletions app/domains/design_pattern/observer/tax_man.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module DesignPattern
module Observer
class TaxMan
def update( changed_employee )
puts("#{changed_employee.name}に新しい税金の請求書を送ります!")
end
end
end
end
34 changes: 34 additions & 0 deletions spec/domains/design_pattern/observer/employee_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
require 'rails_helper'

describe DesignPattern::Observer::Employee do
describe '#salary' do
it 'observe payroll' do
fred = DesignPattern::Observer::Employee.new('Fred', 'Crane Operator', 30000)
payroll = DesignPattern::Observer::Payroll.new
fred.add_observer( payroll )

expected = <<-EOS
Fredのために小切手を切ります!
彼の給料はいま35000です!
EOS

expect { fred.salary = 35000 }.to output(expected).to_stdout
end

it 'observe payroll and tax man' do
fred = DesignPattern::Observer::Employee.new('Fred', 'Crane Operator', 30000)
payroll = DesignPattern::Observer::Payroll.new
fred.add_observer( payroll )
tax_man = DesignPattern::Observer::TaxMan.new
fred.add_observer( tax_man )

expected = <<-EOS
Fredのために小切手を切ります!
彼の給料はいま90000です!
Fredに新しい税金の請求書を送ります!
EOS

expect { fred.salary = 90000 }.to output(expected).to_stdout
end
end
end
17 changes: 0 additions & 17 deletions spec/domains/design_pattern/observer/payroll_spec.rb

This file was deleted.

0 comments on commit d667e9e

Please sign in to comment.