现在需要实现一个需求:我需要在一个窗体中发送一个信息,其余几个窗体都能同时接收到发送的消息。
1.界面:一个管家窗体,1个主窗体,2个订阅者窗体。其中管家窗体为启动窗体。
2.订阅:2个订阅窗体订阅主窗体。
怎么样才能在松耦合的情况下完成这样的有一个需求呢?
附上模型图;
1.我们创建了一个管家类。在管家类中我么可以对所有窗体实现一个显示

2.在我们的主窗体中,我们应创建一个集合类型的属性。该集合为泛型List集合。只能存储实现了接口的类型(MainFrm)
public List<ISetMsg> SetToMsg { get; set; }
3.创建一个接口,接口值有一个方法,该方法是所有订阅者的实现方法

//该接口统一希望订阅窗体的类型的方法。 public interface ISetMsg { void Test(string txt); }
4.订阅者类实现该接口。

public partial class ChildFrm : Form,ISetMsg { public ChildFrm() { InitializeComponent(); } public void Test(string txt) { this.txtMsg.Text = txt; } }

public partial class SecondChildFrm : Form, ISetMsg { public SecondChildFrm() { InitializeComponent(); } public void Test(string txt) { this.txtMsg.Text = txt; } }
5.创建主窗体按钮的点击事件。该事件发生时遍历集合,调用方法传递信息

private void BtnSendMsg_Click(object sender, EventArgs e) { if (SetToMsg == null) { return; } foreach (var item in SetToMsg) { item.Test(this.txtMsg.Text); } this.txtMsg.Clear(); }
6.我们的主窗体与其余窗体就完全的实现了解耦。
。。。。。。。。。。。。。。。。。。。。。。
我么应强迫自己多用解耦的方式去书写代码。