日期:2014-05-18 浏览次数:20966 次
MiddleModule: using System; using System.Collections.Generic; using System.Text; namespace Observer { /// <summary> /// 定义发布消息的委托 /// </summary> /// <param name="sender">发布者</param> /// <param name="msg">消息</param> public delegate void Send(object sender, object msg); /// <summary> /// 观察者的中间模块组建 /// </summary> public class MiddleModule { /// <summary> ///消息发布的事件 /// </summary> public static event Send eventSend; public static void SendMessage(object sender, object msg) { if (eventSend != null) { eventSend(sender, msg); } } } }
namespace WinObserver
{
public partial class FrmMain : Form
{
/// <summary>
/// 构造方法,在构造主窗体的时候就订阅来自FrmChild1的消息
/// </summary>
public FrmMain()
{
InitializeComponent();
MiddleModule.eventSend += new Send(MiddleModule_eventSend);
}
/// <summary>
/// 接收FrmChild1的回传数据
/// </summary>
/// <param name="sender"> </param>
/// <param name="msg"> </param>
void MiddleModule_eventSend(object sender, object msg)
{
FrmChild1 frmChild1 = sender as FrmChild1;
if (null != frmChild1)
{
this.lblMsg.Text = "FrmChild1的回传数据:"+msg.ToString();
}
}
private void btnShow1_Click(object sender, EventArgs e)
{
FrmChild1 frmChild1 = FrmChild1.CreateInstance();
frmChild1.Show();
}
private void btnShow2_Click(object sender, EventArgs e)
{
FrmChild2 frmChild2 = FrmChild2.CreateInstance();
frmChild2.Show();
}
private void btnSend_Click(object sender, EventArgs e)
{
//由Observer模块传递数据
if (String.IsNullOrEmpty(this.txtMsg.Text))
{
MiddleModule.SendMessage(this, String.Empty);
}
else
&nb