Home  >  Article  >  Backend Development  >  C#’s support for the Observer pattern (1)

C#’s support for the Observer pattern (1)

黄舟
黄舟Original
2016-12-21 14:55:511252browse

First of all, let us understand what the observer pattern is. The observer pattern is a behavioral pattern of objects, also called dependency/slave pattern, publish-subscribe pattern, and source-listening pattern. Observer pattern: defines a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated (GOF).

For example, there is an email system in our project. When sending an email, it may be necessary to send SMS and RTX information to notify the email recipient. At this time, you can use the observer mode to design. If you need to add a third notification method in the future, , then our system will easily add new notification methods. The observer pattern is widely used in C#. The most common one is that we use the event listening mechanism of various controls.

There are four types of participants in the implementation of the observer pattern, namely:

1. Abstract subject/target (Subject)

It can have any number of observers and save the observations in a collection object Reference to the observer, and provides an interface for adding and deleting observer objects, usually implemented with an abstract class and interface.

2. Abstract Observer (Observer)

An update interface defined for all specific observers. When the subject/target changes, the specific observers are notified to update themselves. Usually implemented with an abstract class or interface.

3. Concrete Subject/Target (ConcreteSubject)

Store the relevant status in the specific observer object. When its status changes, a notification is sent to all registered observers. The specific subject/target is also called the observed.

4. Concrete Observer (ConcreteObserver)

maintains a reference to a specific subject/target, stores related states consistent with the specific subject/target, and implements an update interface for a specific abstract observer to update its own state Align with subject/goal status.

We use the observer mode to implement a simple email sending system, and when sending the email, we will send SMS and RTX messages to notify the email recipient.

The above is the content of C#’s support for the Observer mode (1). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn