设计模式之观察者模式(Observer Pattern)(二)

80酷酷网    80kuku.com

  server|设计在上例子中传递的信息是一个字符串,当我们点击其中一个radio button,我们可以得到这个radio button的名称(Red Blue Green),将这个名称发送到观察者(Observer)。

Observer提供一个对目标主体(Subject)抽象连接,一个目标主体(Subject)不知道他的观察者(Observer)的任何信息,但是当他改变时可以更新通知发送到各个注册过的观察者(Observer)。

我们也可以使用委托(Delegate)来实现Observer模式

Public Class Subject

'定义委托

Public Delegate Sub SendMessageDelegate(ByVal aPrice As String)

'定义事件

Public Event SendMessage As SendMessageDelegate

Dim _askprice As String



Public WriteOnly Property Message() As String

Set(ByVal Value As String)

_askprice = Value

'引发事件

RaiseEvent SendMessage(_askprice)

End Set

End Property

End Class

在主窗体中:

Dim lscol As New listObs

Dim frcol As New frmD

Public Sub New()

MyBase.New()

Form1 = Me

InitializeComponent()

Dim evh As EventHandler = New EventHandler(AddressOf RadioHandler)

AddHandler opRed.Click, evh

AddHandler opBlue.Click, evh

AddHandler opGreen.Click, evh

lscol.Show() ‘显示两个Observer

frcol.Show()

End Sub

‘处理Radio Button的单击事件

Protected Sub RadioHandler(ByVal sender As Object, ByVal e As EventArgs)

Dim i As Integer

Dim rbut As Windows.Forms.RadioButton = CType(sender, Windows.Forms.RadioButton)

Dim subject As New subject

Dim aDelegate As subject.SendMessageDelegate = New subject.SendMessageDelegate(AddressOf lscol.Add)

Dim aDelegate1 As subject.SendMessageDelegate = New subject.SendMessageDelegate(AddressOf frcol.DrawMessage)

‘布线

AddHandler subject.SendMessage, aDelegate

AddHandler subject.SendMessage, aDelegate1

'AddHandler subject.SendMessage, AddressOf lscol.Add

'AddHandler subject.SendMessage, AddressOf frcol.DrawMessage

subject.Message = rbut.Text

‘撤销布线

RemoveHandler subject.SendMessage, aDelegate

RemoveHandler subject.SendMessage, aDelegate1

End Sub

在listbox窗体和ColorFrame窗体分别定义委托所指向的事件:

‘listbox窗体

Public Sub Add(ByVal mesg As System.String)

lsColors.Items.Add(mesg)

End Sub

‘ColorFrame窗体

Public Sub DrawMessage(ByVal mesg As System.String)

colname = mesg

Select Case mesg.ToLower

Case "red"

Pic.BackColor = Color.Red '

Case "blue"

Pic.BackColor = Color.Blue

Case "green"

Pic.BackColor = Color.Green

End Select

End Sub

这样也可以实现相同的效果。



参考资料:

设计模式:利用C#的Delegate来改进Observer模式 作者:卢彦
探究观察者设计模式

刚开始学习设计模式在.NET中的应用,希望对大家在学习过程中有所帮助!

可以写信给我进行交流!

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: