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

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

黄舟
黄舟Original
2016-12-21 14:56:551177browse

.Net defines a standard pattern for us to apply events. We should abide by the rules for defining events during the application process. A standard event pattern includes four aspects:

1. An event information class inherited from the System.EventArgs type, and the name of this class ends with EventArgs, such as SendMailEventArgs. This class is responsible for saving the event source and sending it to the event listener information of the person. If the event source does not need to pass additional information to the event listener, you can use EventArgs.Empty directly. At this time, we do not need to define our own event information class.

2. The delegate used when defining events (similar to the abstract subject Subject and abstract observer Observer in the observer pattern). The return type of this delegate is void and has two parameters. The first parameter type is Object, and the second parameter type is void. One is System.EventArgs or its subclass, and the name should end with EventHandler, such as:

public delegate void System.EventHandler(Object sender, TeventArgs e) where TeventArgs:EventArgs;

In this way, we no longer need to implement a custom delegate in actual applications. We can directly use this generic delegate to meet the needs of our application events. need.

3. An event source class responsible for notifying event subscribers (similar to the concrete subject ConcreteSubject in the observer pattern). This class contains an event member, which is responsible for providing event subscription and cancellation interfaces to the outside world, and saving their status. ;A method responsible for raising an event to notify all subscribers of this event. This method needs to be a protected virtual method, starting with On and ending with the event name, and accepts a type of System.Eventargs (or subclass) parameters. For example, define an event member:

public event EventHandler SendMail;

Then this method should be:

PRotected virtual void OnSendMail(SendMailEventArgs e){}; The method of expecting an event is probably called a trigger.

This method is responsible for instantiating an event message class, calling the method OnXxx that triggers the event, and passing the event message instance.

4. The event listener class (similar to the ConcreteObserver in the observer pattern) is used to listen to messages sent by the event source. This class is used to define methods that are compatible with events. The format is that the return value is void. There are two parameters, the first parameter type is Object, and the second one is the corresponding event message class. Example: protected void Phone_SendMail(Object sender,EventArgs e)...;

The following rewrites the email sending system in the previous article:

First define an event message class, which is responsible for saving messages sent to the device.

view plaincopy to clipboardprint?
public class SendMailEventArgs:EventArgs                                                                                                                       
                                                                                                                  public class SendMailEventArgs:EventArgs
                                                                                                                                           .
         }
     }

Event source class.

view Plaincopy to Clipboardprint?
Class Mailmanager
{
// mail
public system.net.mailMailMessage Mailmess Bleak}
get {
Return new system.net.mail.mailMessage ();
}}}
// The generic commission provided by the .NET framework defined an event
Public Event EventHandler & LT; gs & gt; sendmail;
// Responsible Methods for triggering events
protected virtual void OnSendMial(SendMailEventArgs e)
                                         if (sendMail != null)                                                                                                                                                        }       
                                                                                                                                                      ject) || string.IsNullOrEmpty(MailMess.Body))                                                                                                   "Failed to send email!");
                                                            use using the subject of the email to instantiate an event information class                                                   new SendMailEventArgs(MailMess.Subject);                                                                                                                                                                                                                                                                                                                                                         Class MailManager {
                                                                                                                                                                                               return new System.Net.Mail.MailMessage();
}
                                  // Define an event using the generic delegate provided by the .net framework            public event EventHandler                                                                                                                                        tArgs e)
                                                                                                               ; sendMail=SendMail;
                                                                                                                                                                                                                                                                    //Responsible for converting external calls into
                                                                                                                               ine("Failed to send email!");
                                                                                                                                                                                                                               . "Send mail: {0}", MailMess.Subject);
                                                                                                                                                                           // Notify all event subscribers
                 this. OnSendMial (sendMailEventArgs); Handler member

public void SendMessage(object sender,SendMailEventArgs e)
WriteLine("Mobile phone message: {0}", e.Message);                                                                                                                                         
           public void SendMessage(object sender,SendMailEventArgs e)                                                                                                                                                                                                       public void SendMessage(object sender,SendMailEventArgs e)                                               Console.WriteLine("RTX information: {0}", e.Message);                                                                          Public void SendMessage(object sender,SendMailEventArgs e)
                              
Console.WriteLine("Mobile phone information: {0}", e.Message); sender,SendMailEventArgs e)
{O Console.writeline ("RTX Information: {0}", E.Message);
}

#Endregion
}



Below is the client call

View Plaincopy to ClipboardPrint?
Class Program {
{
{
{
{
static void Main(string[] args)                                                                                                             mailManager.MailMess.Subject = "Notification"; MailMess.Body = "Observer mode learning.";                                                                                                                                         MailManager.SendMail +                                       . mailManager. SendToMail();//Send an email
                Console.WriteLine("Press any key to continue...")        
                                      ’’s ’ ’s using ’’s ’        through out through out through out out through out out out out out outmb out out out off out's to ‐ ‐‐ ‐‐ ‐‐‐ and ​ to Observer mode support (2) ), please pay attention to the PHP Chinese website (www.php.cn) for more related content!



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