2006.7.19 Li Jianzhong
Publishing-subscription model
If we subscribe to services such as mobile phones and emails, we will be notified of any operations in the amount of our account.
Motivation)
In the process of building software, we need to establish a "Notification dependency" for some objects-the state of an object (target object) changes, and all dependent objects (Observer objects) will be notified. If such dependency is too tight, the software cannot well resist changes.
Using object-oriented technology, you can weaken this dependency and form a stable dependency. To achieve loose coupling of the software architecture.
Intent)
Defines a one-to-many dependency between objects so that when the status of an object changes, all objects dependent on it are notified and automatically updated.
-- Design Pattern GoF
For example, the Observer application
In this design, if other devices need to be notified, we need to modify the BankAccount frequently every time.
Improved Design
Structure)
ConcreteSubject corresponds to the BankAccount In the example, and ConcreteObserver corresponds to Emailer and Mobile.
Key points of the Observer Mode
Using object-oriented abstraction, the Observer mode enables usChange the target and observer independently(Changes in the object-oriented model do not mean code modification, but extension, subclass, or interface implementation), so that the dependency between the two can be loosely coupled.
When the target sends a notification, no observer is required. The notification (which can carry the notification information as a parameter) will be automatically transmitted. The observer decides whether to subscribe to notifications by himself, and the target object knows nothing about this.
In the C # event, the delegate acts as an abstract Observer interface, and the object that provides the event acts as the target object. Delegation is a more loosely coupled design than the abstract Observer interface.
Observer in. NET Framework
In the AccountChange delegate, all objects in the delegate linked list are traversed and called.
Although Emailer does not implement the interface here, it actually implicitly conventions the interface, and its method name may not necessarily be Update, making the loose coupling more flexible.
The + number of the delegate is actually the method for adding a notification to the delegate linked list. The delegate event completes the traversal and Addition and deletion methods for us, however, the implementation principle is the same as that in our first example.
There is no strong dependency between Emailer and BankAccount. The dependency between them depends on the third-party delegation. As long as the delegation is stable, the others will be stable. Therefore, we can regard delegation as an interface. We try to rely only on Delegation, rather than relying on our specific types.
2010.10.19