1 什么是观察者设计模式
- 观察者模式是软件设计模式的一种,定义了对象之间一种一对多的关系,可以减少代码的耦合度。这里使用观察者模式实现不同窗体传值。
2.观察者设计模式 非委托实现
思路图:
使用接口
首先创建一个接口文件,IMessageON.cs,里面有个RecieveMsg方法;
namespace WindowsFormsApplication2
{
public interface IMessageON
{
void RecieveMsg(string str);
}
}
在Main窗体主要起中介作用并打开所有窗体。
代码:
namespace WindowsFormsApplication2
{
public partial class Main : Form
{
public info_send info_send1 { get; set; }
public Main()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
info_send s1 = new info_send();
this.info_send1 = s1;
s1.Show();
info_receive1 r1 = new info_receive1();
// 用接口的形式注册 观察者。
s1.MessageOnList.Add(r1);
r1.Show();
info_receive2 r2 = new info_receive2();
// 用接口的形式注册 观察者。
s1.MessageOnList.Add(r2);
r2.Show();
}
info_send窗体,创建一个接口类型集合并发送数据
代码
namespace WindowsFormsApplication2
{
public partial class info_send : Form
{
public info_send()
{
InitializeComponent();
MessageOnList = new List<IMessageON>(); //集合
}
//这个集合放我们的观察者
public List<IMessageON> MessageOnList { get; set; }
private void button1_Click(object sender, EventArgs e)
{
foreach (var messageOn in MessageOnList)
{
messageOn.RecieveMsg(textBox1.Text);
}
}
}
}
info_receive1 窗体,实现接口,(info_receive2 窗体一样)
namespace WindowsFormsApplication2
{
public partial class info_receive1 : Form,IMessageON //使用接口
{
public info_receive1()
{
InitializeComponent();
}
public void RecieveMsg(string str) //实现接口
{
this.textBox1.Text = str;
}
效果图:
2.观察者设计模式 委托实现
这里还使用委托事件
在Main窗体主要起中介作用并打开所有窗体,代码如下:
namespace WindowsFormsApplication2
{
public partial class Main : Form
{
public info_send info_send1 { get; set; }
public Main()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
info_send s1 = new info_send();
this.info_send1 = s1;
s1.Show();
info_receive1 r1 = new info_receive1();
//事件的形式注册观察者。
s1.Messevent+=r1.SetMsgTextEvent;
//用户委托的形式注册观察者
s1.Message += r1.SetMsgText;
r1.Show();
info_receive2 r2 = new info_receive2();
//事件的形式注册观察者。
s1.Messevent += r2.SetMsgTextEvent;
//用户委托的形式注册观察者
s1.Message += r2.SetMsgText;
r2.Show();
}
}
}
info_send窗体,
namespace WindowsFormsApplication2
{
public partial class info_send : Form
{
public delegate void Mess(string str); //声明委托
public info_send()
{
InitializeComponent();
}
#region 用户委托
public Mess Message { get; set; } //委托
private void button1_Click(object sender, EventArgs e)
{
Message(textBox1.Text);
}
#endregion
#region 使用Event事件
//事件
public event Mess Messevent;
private void button2_Click(object sender, EventArgs e)
{
Messevent(textBox1.Text);
}
#endregion
}
}
nfo_receive1 窗体,(info_receive2 窗体一样)
namespace WindowsFormsApplication2
{
public partial class info_receive1 : Form
{
public info_receive1()
{
InitializeComponent();
}
public void SetMsgTextEvent(string str)
{
this.textBox1.Text = " 事件委托" + str;
}
public void SetMsgText(string str)
{
this.textBox1.Text = " 用户委托" + str;
}
}
}
效果图:(两种效果一样)