Open viphat opened 6 years ago
There are a few similarities between the Observer and Strategy patterns. Both patterns employ an object (the Observer’s subject and the Strategy’s context) that makes calls to another object (the Observer’s observer or Strategy’s strategy). The difference between the two patterns is the purpose and use case. The Strategy pattern relies on the strategy to do the work, while the Observer pattern informs the observers of what is going on with the subject.
How can you make the
Employee
object spread the news about salary changes without tangling it up with the payroll system?Staying Informed
One way to solve this problem is to focus on the fact that the
Employee
object is acting as a source of news. Fred gets a raise and hisEmployee
record shouts out to the world (or at least to anyone who seems interested), “Hello! I’ve got something going on here!” Any object that is interested in the state of Fred’s finances need simply register with hisEmployee
object ahead of time. Once registered, that object would receive timely updates about the ups and downs of Fred’s paycheck.The straightforward way:
The Observer Pattern
Add more observer:
The GoF called this idea of building a clean interface between the source of the news that some object has changed and the consumers of the news the Observer Pattern
Better way to implement Observer Pattern in Ruby
Using module
observable
Abusing the observer pattern
Xét trường hợp một implementation đơn giản như này:
Khi Fred được promote lên vị trí cao hơn (với title mới) và có mức lương cao chót vót (ứng với title mới):
Giả sử một trong các observer có dùng đến title của Fred
Thì khi chạy đoạn code trên, ta sẽ thấy tình trạng inconsistent xuất hiện, vì chúng ta đã cập nhật mức lương của Fred trước khi cập nhật title của anh ấy nên khi
payroll.update
được gọi ở lần đầu tiên (dosalary=
) thì kết quả sẽ hiển thị sai.