Observer-intermediary design pattern (delegate, event implementation), Observer Design Pattern
Subform 1:
// Declare the delegate public delegate void SendMessageDel (string str); public partial class childform1: Form {public childform1 () {InitializeComponent ();} # region uses delegation to implement observer mode // defines a delegated instance // insecure. public SendMessageDel sendMessageDelInstance {get; set;} can be called externally ;} // delegate method private void button#click (object sender, EventArgs e) {sendMessageDelInstance ("delegate observer mode ");} # endregion # region uses events to implement observer mode // defines the event public event SendMessageDel sendMessageEvent; private void button2_Click (object sender, EventArgs e) {sendMessageEvent ("event implements observer mode ");} # endregion}
Main form
Public partial class mainform: Form {public mainform () {InitializeComponent ();} private void button#click (object sender, EventArgs e) {# region delegate implementation observer childform1 c1 = new childform1 (); c1.Show (); // form 2/3 is registered to delegate childform2 c2 = new childform2 (); c1.sendMessageDelInstance + = c2.SetMessage; c2.Show (); childform3 c3 = new childform3 (); c1.sendMessageDelInstance + = c3.SetMessage; c3.Show (); # endregion} private void button2_Click (object sender, EventArgs e) {# region event implements the observer mode childform1 c1 = new childform1 (); c1.Show (); // form 2/3 registers with the event childform2 c2 = new childform2 (); c1.sendMessageEvent + = c2.SetMessage; c2.Show (); childform3 c3 = new childform3 (); c1.sendMessageEvent + = c3.SetMessage; c3.Show (); # endregion }}
Subform 2/3
Public partial class childform2: Form {public childform2 () {InitializeComponent ();} // delegate method public void SetMessage (string str) {this. textBox1.Text = str + "" + DateTime. now. toString ();} // event Method public void SetMessage_event (string str) {this. textBox1.Text = str + "" + DateTime. now. toString ();}}
Difference: events are safe and can only be triggered within the class.