First, overview:
Defines a one-to-many dependency between objects, and when the state of an object changes, all objects that depend on it are notified and automatically updated. [GOF "Design pattern"]
Look at Terrylee's. NET design pattern (19): Observer mode (Observer pattern), the individual thought that the derivation of the model is clear, but the example of the feeling is not very good, and the actual project or a bit out. Just have a small project in hand to apply this mode, do not know whether the application is correct, if the understanding is not in place, please correct me. This article is right. NET design pattern (19): A supplement to the Observer model (Observer pattern), I wonder if Terrylee is allowed.
Second, the Observer Pattern structure diagram:
Third, the actual case:
A monitoring system, needs to be based on certain changes in the system alarm, alarm mode has email, SMS and many other, may change later. How to deduce to the Observer mode is no longer said (if need to add, general reference Terrylee article can understand).
Ialarm is the alarm interface. When our system needs to add alarm mode, we only need to implement the Ialarm warn method. Email class is the realization of email alarm, SMS class is the realization of SMS alarm.
Monitorcontainer is the monitor (abstract class) equivalent to the observer. Only responsible for notification changes, when subclasses call the Notify method it will notify the alarm module alarm, such as email and SMS (SMS).
Netmonitor is one of the specific monitoring modules, inherited from Monitorcontainer. The Notify method of the parent class is invoked when a problem is found in the system network.
Monitorcontainer in the addalarm here is omitted (add the Alarm module object to the Arrarylist)
The Notify method is to set up the Alarm module objects under foreach. (Refer to.) NET design pattern (19): Observer mode (Observer pattern) article in the code)