子窗体1:
//声明一委托 public delegate void SendMessageDel(string str); public partial class childform1 : Form { public childform1() { InitializeComponent(); } #region 用委托实现观察者模式 //定义一委托的实例 //不安全,可以被外部调用 public SendMessageDel sendMessageDelInstance { get; set; } //委托的方法 private void button1_Click(object sender, EventArgs e) { sendMessageDelInstance("委托实现观察者模式"); } #endregion #region 用事件实现观察者模式 //定义事件 public event SendMessageDel sendMessageEvent; private void button2_Click(object sender, EventArgs e) { sendMessageEvent("事件实现观察者模式"); } #endregion }
主窗体
public partial class mainform : Form { public mainform() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { #region 委托实现观察者 childform1 c1 = new childform1(); c1.Show(); //窗体2/3注册到委托 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 事件实现观察者模式 childform1 c1 = new childform1(); c1.Show(); //窗体2/3注册到事件 childform2 c2 = new childform2(); c1.sendMessageEvent += c2.SetMessage; c2.Show(); childform3 c3 = new childform3(); c1.sendMessageEvent += c3.SetMessage; c3.Show(); #endregion } }
子窗体2/3
public partial class childform2 : Form { public childform2() { InitializeComponent(); } //委托的方法 public void SetMessage(string str) { this.textBox1.Text = str+" "+DateTime.Now.ToString(); } //事件的方法 public void SetMessage_event(string str) { this.textBox1.Text = str+" "+DateTime.Now.ToString(); } }
区别:事件是安全的,只能在类的内部触发。