diff --git a/app/domains/design_pattern/observer/employee3.rb b/app/domains/design_pattern/observer/employee3.rb new file mode 100644 index 0000000..f8eba0f --- /dev/null +++ b/app/domains/design_pattern/observer/employee3.rb @@ -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 diff --git a/app/domains/design_pattern/observer/subject3.rb b/app/domains/design_pattern/observer/subject3.rb new file mode 100644 index 0000000..389dc6b --- /dev/null +++ b/app/domains/design_pattern/observer/subject3.rb @@ -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 \ No newline at end of file diff --git a/spec/domains/design_pattern/observer/employee_spec.rb b/spec/domains/design_pattern/observer/employee_spec.rb index e6d5fec..ae285e4 100644 --- a/spec/domains/design_pattern/observer/employee_spec.rb +++ b/spec/domains/design_pattern/observer/employee_spec.rb @@ -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 \ No newline at end of file