首页 > 开发 > 综合 > 正文

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

2024-07-21 02:16:29
字体:
来源:转载
供稿:网友
在上例子中传递的信息是一个字符串,当我们点击其中一个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中的应用,希望对大家在学习过程中有所帮助!

可以写信给我进行交流!
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表