我现在正在阅读头部设计模式,虽然本书非常出色,但我也希望看到它们在现实世界中是如何实际使用的.
如果你知道设计模式使用的一个很好的例子(最好是在OSS程序中,所以我们可以看一下:),请在下面列出.
对我来说,观察者模式的一个令人惊叹的时刻是意识到它与事件的关联有多么紧密。考虑一个需要在两种窗体之间实现松散通信的 Windows 程序。这可以通过观察者模式轻松实现。
下面的代码显示了 Form2 如何触发事件以及注册为观察者的任何其他类如何获取其数据。
请参阅此链接以获取出色的图案资源: http://sourcemaking.com/design-patterns-and-tips
表格1的代码:
namespace PublishSubscribe
{
public partial class Form1 : Form
{
Form2 f2 = new Form2();
public Form1()
{
InitializeComponent();
f2.PublishData += new PublishDataEventHander( DataReceived );
f2.Show();
}
private void DataReceived( object sender, Form2EventArgs e )
{
MessageBox.Show( e.OtherData );
}
}
}
Run Code Online (Sandbox Code Playgroud)
Form2的代码
namespace PublishSubscribe
{
public delegate void PublishDataEventHander( object sender, Form2EventArgs e );
public partial class Form2 : Form
{
public event PublishDataEventHander PublishData;
public Form2()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e )
{
PublishData( this, new Form2EventArgs( "data from form2" ) );
}
}
public class Form2EventArgs : System.EventArgs
{
public string OtherData;
public Form2EventArgs( string OtherData )
{
this.OtherData = OtherData;
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19378 次 |
最近记录: |