Delegate (2): use events to encapsulate delegate variables and

Source: Internet
Author: User

Delegate (2): use events to encapsulate delegate variables and



Next article: Delegation (1): Delegation and Methods



We often see this code when studying the design pattern:






It can be said that delegation and events are often used together, and it is quite troublesome. In addition, I think the delegation is quite good. Why should I join the event? It's complicated. OK. Here is a small example to illustrate why the event is used.


The class structure in the example (we have improved the instance in the previous blog, dispersed the methods into different classes, and tried to simulate the actual call ):





The first is the simplest GreetingMethod class code:



Namespace delegation and event {public class GreetingMethod {/// <summary> /// Method for speaking good morning in English /// </summary> /// <param name = "name "> </param> /// <returns> </returns> public static void EnglishGreeting (string name) {Console. writeLine ("good, morning! "+ Name );} /// <summary> /// method of greeting in Chinese /// </summary> /// <param name = "name"> </param> /// <returns> </returns> public static void ChineseGreeting (string name) {Console. writeLine ("good morning, baby ~~~ "+ Name );}}}




In the GreetingMethod class, we put the specific Greeting method in this class. Here, we will not consider the future change factors.



Next is the GreetingManager class. In this class, we move the original GreetPeople method to this class:




Namespace delegate and event {// delegate definition // 1. Delegate: The delegate appears at the same position as string, so GreetingDelegate should also be of the same type, however, the delegate declaration method and class are completely different. // 2. The delegate is indeed compiled into a class during compilation. Because delegate is a class, you can declare the delegate in any place where the class can be lifecycle. Public delegate void GreetingDelegate (string name ); /// <summary> /// class for managing method calls /// </summary> public class GreetingManager {# region defines the delegate variable inside the class /// the first improvement: declare the delegate1 variable // public GreetingDelegate delegate1; # endregion # region after using the event public event GreetingDelegate MakeGreet; # endregion // after using the delegate, improvements to the GreetPeople method # region passes the delegate as a method parameter to the function // <summary> /// call the greeting method /// </summ Ary> ///// <param name = "name"> name </param> //// <param name = "MakeGreeting"> name of the method to be called </ param> // public void GreetPeople (string name, greetingDelegate MakeGreeting) // {// MakeGreeting (name); //} # endregion # region calls the member variable delegate1 directly within the method // public void GreetPeople (string name) // {// if (delegate1! = Null) {// If the delegate variable has been assigned a value // delegate1 (name ); // then directly call //} # endregion # region using event public void GreetPeople (string name) {MakeGreet (name );} /***** the only difference between the MakeGreet event Declaration and the previous delegate variable delegate1 Declaration is that an event keyword is added. ** So... ** 1. Declaring an event is similar to declaring a variable of the encapsulated delegate type. ** 2. The event encapsulates the delegate variables, similar to the previous get, set field *******/# endregion }}


Next, call the client:


Namespace delegate and event {class Program {static void Main (string [] args) {# region puts GreetingManager into other classes and the client calls it // GreetingManager manager = new GreetingManager (); // manager. greetPeople ("paddy field", GreetingMethod. englishGreeting); // manager. greetPeople ("vac", GreetingMethod. chineseGreeting); # endregion # bind multiple region methods to the same delegate variable // GreetingManager = new GreetingManager (); // GreetingDelegate delegate1; // dele Gate1 = GreetingMethod. englishGreeting; // delegate1 + = GreetingMethod. chineseGreeting; // manager. greetPeople ("", delegate1); # endregion # example of client call after the region declares delegation within the GreetingManager class // GreetingManager gm = new GreetingManager (); // gm. delegate1 = GreetingMethod. englishGreeting; // gm. delegate1 + = GreetingMethod. chineseGreeting; // gm. greetPeople ("paddy field", gm. delegate1); // PS: Although there is no problem with this operation, this statement is very strange and calls gm. gre EtPeople ("paddy field such as ya", gm. delegate1); when the method is used, the delegate1 field of gm is passed again; but delegate1 is in gm. So we need to improve it again here. # Endregion # Call after region improves the GreetPeople method of the GreetingManager class // GreetingManager gm = new GreetingManager (); // gm. delegate1 = GreetingMethod. englishGreeting; // gm. delegate1 + = GreetingMethod. chineseGreeting; // gm. greetPeople (""); // during this call, name is directly input, and delegate is no longer required. # endregion # region continues to be considered, thinking ............ /** although the desired results are achieved, there are still problems. * 1. Here, there are no differences between delegate1 and string variables used in peacetime. Not all member variables should be declared as public. According to the principle of information hiding, we should try to encapsulate data. * 2. But if delegate1 is declared as private, how do we assign a value to it? If a value cannot be assigned, how can I register it? * 3. If delegate1 is declared as public, it can be modified at will, undermining encapsulation. * ** 4. To solve the problem, use event ............... * // # endregion # the call after region uses the event // GreetingManager gm = new GreetingManager (); // note that the first time "+ =" is used ", different from directly using the delegate // gm. makeGreet + = GreetingMethod. englishGreeting; // gm. makeGreet + = GreetingMethod. chineseGreeting; // gm. greetPeople ("paddy fields such as ya"); # endregion }}}


Next we will describe the improvement process for this small Demo:


We use delegation mainly to achieve [convenient] [secure] Call methods.


To facilitate the call, we first declare the delegate1 variable in the GreetingManager class, and then find that this is done,




When calling the above method, it is strange to assign the member variables of this class to the method of this class in the method of this class, why don't we directly call its member variables in the method of this class, so we removed the second parameter in the above method, but there is still a problem, is the access problem of class members.


In principle, we should minimize the access permissions of class members to achieve the encapsulation effect, but now, we directly assign the variable members that should be encapsulated on the client.



To solve this problem, let's look back at how we used to hide fields:




Yes, we use property to control access to internal private member variables.



However, the access control for delete operations seems simpler. When we declare the delegate, we can add an event in front of it:



In this way, access control is completed in disguise.




 Summary:


To sum up the benefits of event introduction:


1. event encapsulates the variables of the delegate type, which is equivalent to the property customized for the delegate type ).

 

2. Using events not only provides better encapsulation than delegation, but also limits the ability to contain event types.







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.