C # delegation and game application,

Source: Internet
Author: User

C # delegation and game application,

C # delegation and game application

1. What is delegation?

In C/C ++, there is a function pointer concept, that is, a pointer to a function. When we call this pointer, it is equivalent to calling the function pointed to by the pointer, which is a function of the function pointer, and another function is to take itself as a parameter of other functions.

However, pointers directly access memory units. Improper use of pointers by programmers often leads to errors. Therefore, as a type-safe language, pointers are generally not recommended for C #. For example, when using a function pointer as a parameter, you can use any pointer as a parameter, because they are all 32-bit integer variables, they do not provide any other information, such as the number of function parameters, parameter types, and return values. Therefore, the concept of delegation is introduced in C.

Let's first look at a simple delegated instance:

Using System; using System. collections. generic; using System. text; namespace DelegateTest {class program {delegate void MyDelegateTest (int x); private static void test1 (int x) {Console. writeLine ("output square" + (x * x);} private static void test2 (int x) {Console. writeLine ("output and" + (x + x);} static void Main (string [] args) {int a = 2; MyDelegateTest delegateTest; delegateTest = new MyDelegateTest (test1); // delegateTest = test1; // delegateTest + = test1; delegateTest + = test2; delegateTest ();}}}

 

2. Development of delegation in C #

The above is a simple example of delegation. Here we will not describe the specific implementation. Basically, the delegate is similar to the declaration and implementation of a class. First, declare a delegate type with the delegate keyword (here, note that the declared return type and the type parameter must be the same as the corresponding method later ); then declare and instantiate a delegate type variable, and finally call the delegate. Note that every method added to the Delegate will be called, and we do not care about how these methods are implemented.

Prior to C #2.0, the definition of delegation was implemented through the above steps. in C #2.0, the concept of anonymous method was introduced, which simplifies the writing of delegation. For example, we need to write:

DelegateTest = new MyDelegateTest (test1 );

Now it can be simplified:

DelegateTest = delegate (int x) {return x * x ;}

In C #3.0, lambda expressions in functional languages are introduced for further simplification:

DelegateTest = x => {return x * x;} or directly x => x * x;

In C #4.0, another generic delegation was introduced. In fact, a generic restriction was added to the definition:

DelegateT MyDelegateTest <T> (T x); 3. the observer mode through delegation is a common mode in the design mode. In the example of life, it is the subscriber who pays attention to the publisher. When the subscriber has an update, the messages will be pushed to those subscribers. In C #, delegate can be used to implement the observer mode:
Using System; using System. collections. generic; using System. text; namespace ObserverModel {class Program {// -------------------------------------------------------------------- // delegate to act as the public delegate void DelegateSender (object sender ); // -------------------------------------------------------------------- // Publisher class public class Publisher {public DelegateSender SenderEvent; public string Info ;//--- ----------------------------------------------------------------- Public Publisher (string info) {this. info = info;} // add and delete the subscriber public void AddObserver (DelegateSender ob) {SenderEvent + = ob;} public void RemoveObserver (DelegateSender ob) {SenderEvent-= ob ;}//------------------------------------------------------------ ---------- // The publisher updates public void Update () {if (SenderEvent! = Null) {SenderEvent (this) ;}/// Subscriber class 1 public class Subscriber {public string Name; public Subscriber (string name) {this. name = name;} public void DoSomething (Object sender = null) {Console. writeLine ("subscriber 1 Operations") ;}/// Subscriber2 public class Subscriber2 {public string Name; public Subscriber2 (string name) {this. name = name;} public void DoSomething2 (Object sender = null) {Console. writeLine ("subscriber 2 Operations") ;}} static void Main (string [] args) {Publisher publisher = new Publisher ("Publisher "); subscriber sub1 = new Subscriber ("Subscriber 1"); Subscriber2 sub2 = new Subscriber ("Subscriber 2"); // Add a Subscriber publisher. addObserver (new DelegateSender (sub1.DoSomething); publisher. addObserver (new DelegateSender (sub2.DoSomething); publisher. update (); // remove the subscriber publisher. removeObserver (new DelegateSender (sub1.DoSomething); publisher. update (); Console. readLine ();}}}

  

The advantages and disadvantages of the observer mode are also discussed here:

A. The observer mode establishes an abstract coupling between the subscriber and the publisher. The publisher knows only one subscriber list. It abstracts the specific publisher and subscriber and reduces the coupling between them. B. The observer mode supports broadcast communication. The publisher reminds all registered subscribers to send a notification. C. If a publisher has many direct or indirect subscribers, it takes some time to notify all subscribers. d. If there is a dependency loop between the publisher and the subscriber, the system will crash;

E. The Subscriber knows that the publisher has changed, but does not know how the publisher has changed.

 

4. Delegated use in the game

Some messaging mechanisms in the game are implemented through delegation. Taking attribute changes in the game as an example, at the beginning of the Declaration cycle on the interface, we call: sysTem. addUIListener (DgMsgID. netRes_Profile, OnProfile); add a response method to the key corresponding to our delegate dictionary;

At the end of the lifecycle of the interface, we call: Messenger. RemoveListener (DgMsgID. NetRes_Profile, OnProfile); To remove this method from the corresponding key on the delegate dictionary.

When the data we receive from the server updates the role attribute, the message is broadcast and all methods added to the key on the delegate dictionary are called: Messenger. broadcast <PlayerProfile> (DgMsgID. dgMsg_UpDatePlayerProfile, response. profile );

In the Messenger class, the above method is actually used to add, damage, and call the corresponding key on the delegate dictionary.

Another typical application is the UIEventListener class defined by NGUI. This class defines many custom delegates for processing various UI operation responses, such:

public delegate void VoidDelegate (GameObject go);public delegate void BoolDelegate (GameObject go, bool state);public UIEventListener.VoidDelegate onClick;public UIEventListener.BoolDelegate onPress;void OnClick (){ if (onClick != null) onClick(gameObject); }void OnPress (bool isPressed){ if (onPress != null) onPress(gameObject, isPressed); }

 

It is also very easy to use, such:

UIEventListener.Get(targetObj).onPress += onPressHandler;

  

This article reference: http://www.cnblogs.com/zhili/p/ObserverPattern.html related design patterns of the article, benefited a lot.

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.