The information passed in the previous example is a string, when we click on one of the Radio Button, we can get the name of this Radio button (Red Blue Green), send this name to the Observer.
Observer provides an abstract connection to the target subject, a target body (Subject) does not know any information, but when he changed, it can update the notification to the observer (Observer) .
We can also use delegate to implement OBServer mode
Public Class SUBJECT
'Definition commission
Public Delegate subsessageDelegate (Byval Aprice As String)
'Defining events
Public Event SendMessage As SendMessageDelegate
DIM _ASKPRICE AS STRING
Public Writeonly Property Message () AS STRING
Set (byval value as string)
_ASKPRICE = Value
'Triggering events
RaiseEvent SendMessage (_ASKPRice)
End set
End Property
END CLASS
In the main form:
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 () 'shows two Observer
frcol.show ()
End Sub
'Handling Radio Button Click Event
Protected Sub RadioHandler (Byval E 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 adlegate as subject.sendMessageDelegate = new subject.sendMessageDelegate (addressof lscol.add)
Dim adlegate1 as subject.sendMessageDelegate = new subject.sendMessageDelegate (Addressof frsdrawMessage)
'wiring
AddHandler Subject.sendMessage, Adlegate
AddHandler Subject.sendMessage, Adlegate1
'AddHandler Subject.sendMessage, Addressof Lscol.add
'AddHandler Subject.sendMessage, Addressof frcol.drawMessage
Subject.Message = rbut.text
'Revoking wiring
RemoveHandler Subject.sendMessage, Adlegate
RemoveHandler Subject.sendMessage, Adlegate1
End Sub
In the Listbox form and the ColorFrame form, the events pointed to by the delegate:
'Listbox form
Public Sub Add (Byval Mesg As System.String)
Lscolors.Items.Add (MESG)
End Sub
'Colorframe Form
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
This can also achieve the same effect.
Reference:
Design Patterns: the use of C # Delegate to improve the Observer pattern of: Lu Yan explore the observer design pattern
I just started learning the design mode in .NET, I hope to help everyone in the learning process! Can write let me exchange!