/*******************************主窗体 中介协调被观察者和观察者的关系*********************************************/
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();
}
private void btnOpen_Click(object sender, EventArgs e)
{
ChildFrm1 frm1 = new ChildFrm1();
frm1.Show();
ChildFrm2 frm2 = new ChildFrm2();
frm1.Observers.Add(frm2);
frm2.Show();
ChildFrm3 frm3 = new ChildFrm3();
frm1.Observers.Add(frm3);
frm3.Show();
}
}
}
/*****************************************子窗体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 ChildFrm1 : Form
{
public ChildFrm1()
{
InitializeComponent();
}
//存储所有的观察者,靠中介管理观察者,发布者根本不知道观察者的存在
public List
private void btnSendMsg_Click(object sender, EventArgs e)
{
//发布消息给所有观察者
foreach (var observer in Observers)
{
observer.RecevieMsg("----");
}
}
}
}
/*******************************子窗体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
{
//观察者
public partial class ChildFrm2 : Form,IMessageOn
{
public ChildFrm2()
{
InitializeComponent();
}
public void RecevieMsg(string str)
{
this.txtMsg.Text = str + " " + DateTime.Now.ToString();
}
}
}
/*************************************子窗体3 观察者********************************************/
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,IMessageOn
{
public ChildFrm3()
{
InitializeComponent();
}
public void RecevieMsg(string str)
{
this.txtMsg.Text = str + " " + DateTime.Now.ToString();
}
}
}
/******************************观察者需要实现的接口**************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AgentPattern
{
public interface IMessageOn
{
void RecevieMsg(string str);
}
}