Skip to content

Commit

Permalink
変更に追従する:Observer #75
Browse files Browse the repository at this point in the history
・5.4 オブザーバとしてのコードブロック

EFROR-62
  • Loading branch information
k2works committed Aug 18, 2017
1 parent 28c6cf0 commit 4ddcf46
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
22 changes: 22 additions & 0 deletions app/domains/design_pattern/observer/employee3.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module DesignPattern
module Observer
class Employee3
include Subject3
attr_reader :name
attr_accessor :title, :salary

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

def salary=(new_salary)
@salary = new_salary
notify_observers
end
end
end
end
23 changes: 23 additions & 0 deletions app/domains/design_pattern/observer/subject3.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module DesignPattern
module Observer
module Subject3
def initialize
@observers = []
end

def add_observer(&observer)
@observers << observer
end

def delete_observer(observer)
@observers.delete(observer)
end

def notify_observers
@observers.each do |observer|
observer.call(self)
end
end
end
end
end
19 changes: 19 additions & 0 deletions spec/domains/design_pattern/observer/employee_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,22 @@
end
end
end

describe DesignPattern::Observer::Employee3 do
describe '#salary' do
it 'observe payroll' do
fred = DesignPattern::Observer::Employee3.new('Fred', 'Crane Operator', 30000)
fred.add_observer do |change_employee|
puts("Cut a new check for #{change_employee.name}!")
puts("His salary is now #{change_employee.salary}!")
end

expected = <<-EOS
Cut a new check for Fred!
His salary is now 35000!
EOS

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

0 comments on commit 4ddcf46

Please sign in to comment.