Asp.Net进阶/管家模式+发布订阅模式:练习

现在需要实现一个需求:我需要在一个窗体中发送一个信息,其余几个窗体都能同时接收到发送的消息。

1.界面:一个管家窗体,1个主窗体,2个订阅者窗体。其中管家窗体为启动窗体。

2.订阅:2个订阅窗体订阅主窗体。

怎么样才能在松耦合的情况下完成这样的有一个需求呢?

附上模型图;

1.我们创建了一个管家类。在管家类中我么可以对所有窗体实现一个显示

 Master  

2.在我们的主窗体中,我们应创建一个集合类型的属性。该集合为泛型List集合。只能存储实现了接口的类型(MainFrm)

   public List<ISetMsg> SetToMsg { get; set; }

3.创建一个接口,接口值有一个方法,该方法是所有订阅者的实现方法

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

4.订阅者类实现该接口。

 public partial class ChildFrm : Form,ISetMsg
    {
        public ChildFrm() {
            InitializeComponent();
        }

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

        public void Test(string txt) {
            this.txtMsg.Text = txt;
        }
    }
SecondChildFrm

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();
        }
View Code

6.我们的主窗体与其余窗体就完全的实现了解耦。

。。。。。。。。。。。。。。。。。。。。。。

我么应强迫自己多用解耦的方式去书写代码。

posted @ 2019-09-05 20:59  JetMe  阅读(350)  评论(0编辑  收藏  举报