Delegate (delegate) c # simple example,
Delegate (delegate) c # simple example
Key points: the mode enables the dependency between the target and the observation to be loosely coupled and the notification will be automatically transmitted.
Example: After a player hits an enemy, a series of changes occur: An explosion occurs after the attack, and one enemy is missing ....
Namespace adapterpattern {public partial class observerDelegateForm: Form {public observerDelegateForm () {InitializeComponent (); BaseData. enemyNumber = 100;} private void btnDisplay_Click (object sender, EventArgs e) {ExplosionEvent explosionEvent = new ExplosionEvent (); // observer 1 Enemy enemy = new Enemy (); // observer 2 player p1 = new player1 (); p1.Update + = new EventHandler (explosionEvent. explosionMax ); // Delegate to the observer 1 p1.Update + = new EventHandler (enemy. decrease); // Add the observer 2 listBox1.Items to the delegate. add (p1.Display () ;}} public static class BaseData // data transfer station {public static string DisplayString {get; set ;} public static int EnemyNumber {get; set ;}} public delegate void EventHandler (); // delegate the event handler public abstract class player {public event EventHandler Update; // declare an event update protected virtual void Policy () // pair Add event Execution Notification {if (Update! = Null) {Update () ;}} public abstract string Display () ;}public class player1: player {public override string Display () {Policy (); // notification observer; return BaseData. displayString + BaseData. enemyNumber. toString () ;}} public class ExplosionEvent // observer 1 {public void ExplosionMax () {BaseData. displayString = "";} public void ExplosionMin () {BaseData. displayString = "show small explosion ";}//.....} public class Enemy // observer 2 {public void Decrease () {BaseData. enemyNumber-= 1; // "Reduce the number of enemies by 1 ";}//.....}}