The Observer pattern (sometimes referred to as the Publish/subscribe model) is one of the software design patterns.
In this pattern, a target object manages all the observer objects that are dependent on it and actively notifies it when its state changes.
This is usually done by calling the methods provided by the various observers.
When implementing the observer pattern, it should be noted that the interaction between the observer and the observed object cannot
Manifest as a direct call between classes, otherwise it will make the observer and the observed object tightly coupled,
Fundamentally violates the principle of object-oriented design. Whether the Observer "observes" the object,
Or the observer who "informs" the observer of his or her changes should not be called directly.
The popular point is that a object (observed) informs another (Observer) of what has changed, what has changed, and what you are going to do is none of my business. The degree of coupling is reduced ...
The following example uses the Ruby module to implement a more traditional observer pattern. The advantage of using module is that the subject class may be subclasses of other base classes, and Mixin implements similar multiple inheritance effects.
Module Subject
def initialize
@observers = []
end
def add_observer ob
@observers << ob
End
def delete_observer ob
@observers. Delete ob
end
def notify_observers
@observers. ob|
Ob.update self end end
class Employee
include Subject
attr_reader:name: Title
attr_reader:salary
def initialize name, title, Salary
super ()
@name = name
@title = title< c24/> @salary = Salary
end
def salary=new_salary
@salary = new_salary
notify_observers
End
end
class taxman
def update obj
puts ' #{obj.name} now has a salary of #{obj.salary} '
end End
Jack = employee.new (' Jack ', ' Prgramer ', 3000)
jack.add_observer (taxman.new)
jack.salary = 3000
We can implement subject module ourselves, but this is a little superfluous, because the Ruby core library itself contains the observable module, and we just need to mixin it to the code.
Require ' observer '
class Employee
include observable
attr_reader:name,: Title: Salary
def Initialize name, title, salary
@name = name
@title = Title
@salary = Salary
end
def salary= (new_ Salary)
@salary = new_salary
changed
notify_observers (self) End
# salary= End
# Employee
The changed method must be called before notify_observers to indicate that a change has actually occurred or the Notify_observers method is invalid.