Commissioned by decoupling

Posted by subscription mode / Client Mode

Not directly call its members between the subject and the object. If direct calls to other objects so that members of a tightly coupled.

--------1.

1. Remove the system we are ready to form. Create a form application

2. Create two form objects, a child forms a parent form

3. Program the program to modify the program startup form parent form

--------2.

1. Add the same controls as our two forms

2. Space same name

--------3.

Open the parent form's code

 

 public ChildFrm ChildFrm { get; set; }//父窗口属性
        private void ParentFrm_Load(object sender, EventArgs e) {
            this.ChildFrm = new ChildFrm();          
            ChildFrm.Show();
        }

--------4.

We are here to add the role of the code are:

Add a delegate for us between the object and the object of decoupling exists.

We need an object, we try to avoid coupling between image and object. The commission to prepare for the following

   public Action<TextBox> SendToChild { get; set; }//委托{可重用性}
        public ChildFrm ChildFrm { get; set; }//父窗口属性
        private void ParentFrm_Load(object sender, EventArgs e) {
            this.ChildFrm = new ChildFrm();
            SendToChild += ChildFrm.TestString;//多播委托,此委托链接一个方法,方法会转换为委托实例。
            ChildFrm.ObjectToSend(this);
            ChildFrm.Show();
        }

--------5.

创建了一个工厂方法,该方法我们用来检查传递进来的参数是否有错误的存在

  public void TestString(TextBox x) {//根据外面传来的值我们决定是否操作。 
            this.txtMsg.Text = x.Text;
          }

--------6.

我们在子窗体中声明了一个方法,该方法只处理传递进来的一个参数,与外部对象实现了一种解耦

  public static class Control
    {
        public static void ShowChildSendControl<T>(Action<T> actio, T x) {//工厂方法,检查是否曾在错误
            try
            {
                if (actio != null || x != null)
                    actio.Invoke(x);
                return;
            }
            catch
            {
                Console.WriteLine("出现异常");
            }
        }
    }

--------7.

添加了一个触发按钮的事件,该事件触发时内部会调用我们的委托,该委托已经指向了一个方法,这个委托作为工厂方法的一个参数传递,目的在于我们在工厂方法内进行检查,提高了代码的复用性。

  private void BtnSendMsg_Click(object sender, EventArgs e) {//父窗口像别的窗口传值
            Control.ShowChildSendControl(this.SendToChild, this.txtMsg);
            this.txtMsg.Clear();
        }

 

Guess you like

Origin www.cnblogs.com/JetMe/p/11462241.html