/******************************主窗体 中介***************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AgentPattern
{
public partial class MainFrm : Form
{
//中介
public MainFrm()
{
InitializeComponent();
}
ChildFrm1 frm1 = null;
private void btnOpen_Click(object sender, EventArgs e)
{
frm1 = new ChildFrm1();
frm1.Show();
ChildFrm2 frm2 = new ChildFrm2();
//观察者的方法注册到被观察者的委托中
frm1.SendMsg += frm2.RecevieMsg;
frm2.Show();
ChildFrm3 frm3 = new ChildFrm3();
//观察者的方法注册到被观察者的委托中
frm1.SendMsg += frm3.RecevieMsg;
frm3.Show();
}
private void btnInvokeDelegete_Click(object sender, EventArgs e)
{
//可以在定义委托的外部触发,不安全
frm1.SendMsg("--------");
}
}
}
/*********************************被观察者*****************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AgentPattern
{
public delegate void SendMsgDel(string msg);
//发布消息
public partial class ChildFrm1 : Form
{
public ChildFrm1()
{
InitializeComponent();
}
//在被观察者中定义委托实例
public SendMsgDel SendMsg;
private void btnSendMsg_Click(object sender, EventArgs e)
{
//发布消息给所有观察者
SendMsg("----");
}
}
}
/***********************观察者1**************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AgentPattern
{
//观察者
public partial class ChildFrm2 : Form
{
public ChildFrm2()
{
InitializeComponent();
}
public void RecevieMsg(string str)
{
this.txtMsg.Text = str + " " + DateTime.Now.ToString();
}
}
}
/***************************观察者2***********************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AgentPattern
{
//观察者2
public partial class ChildFrm3 : Form
{
public ChildFrm3()
{
InitializeComponent();
}
public void RecevieMsg(string str)
{
this.txtMsg.Text = str + " " + DateTime.Now.ToString();
}
}
}