473,553 Members | 2,852 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Observer and Event design pattern.

Hello all,

I have the requirement to produce source code that produces an object
hierarchy.

Example:

Root
|
Folder 1
|
Object 1
Object 2
Folder 2
|
Object 1

These objects will displayed in a treeview much in the same way that MS
explorer does. The same object can appear under many folders. A user is
able to delete objects in view. When this occurs I must remove the other
object from any other folders. Still with me?

Problems... To solve this problem I implemented an observer pattern. This
observer has a hashtable of all created objects. When one is deleted the
observer notifies the other objects and they are responsible for removing
themselves. This seems to work great, but after digging around in MSDN I
found documentation that stated Microsoft did not implement standard
interfaces for the observer pattern because the 'Event pattern' using
delegates and events was the recommended way to implement an observer
pattern. I have sample source code that shows the 'Event Pattern' but I
cannot see a way to solve my problem using it! I know I have solved the
problem using a regular observer pattern but I would like to understand how
the event pattern could have been used?

Any help would be appreciated.

Thanks

From
http://www.fawcette.com/dotnetmag/20...dfox/page3.asp
VB .NET . Implement the Event Pattern
Listing 1. This simple example implements the .NET Framework Event Pattern
that's based on the Observer pattern. In this example the Product class
declares a Delegate that's used to define the signature of an event fired
when the number of items in stock changes. The client (Observer) can then
create a new Delegate object and dynamically bind it to the event fired by
the Product. The common language runtime handles the notification of the
observers by invoking the Delegate when the RaiseEvent statement executes.
In this case, VB.NET includes the Delegate, Event, RaiseEvent, AddHandler,
and RemoveHandler keywords to work with Delegates, while C# includes the
Delegate and event keywords.
Public Class Product

' Delegate to represent the event
Delegate Sub ProductStockCha ngedHandler( _
ByVal sender As Object, _
ByVal e As ProductStockCha ngedEventArgs)
' Declare an event that uses the delegate
Public Event ProductStockCha nged As _
ProductStockCha ngedHandler

' Instance data for a product
Dim _inStock As Integer
Dim _productId As Integer

Public Sub New(ByVal productId As Integer)
_productId = productId
End Sub

Public Property ProductId() As Integer
Get
Return _productId
End Get
Set(ByVal Value As Integer)
_productId = Value
End Set
End Property

Public Property InStock() As Integer
Get
Return _inStock
End Get
Set(ByVal Value As Integer)
_inStock = Value
' Call the protected method to fire the event
OnProductStockC hanged()
End Set
End Property

' Method used to fire the event
Protected Sub OnProductStockC hanged()
RaiseEvent ProductStockCha nged(Me, _
New ProductStockCha ngedEventArgs( _
Me.ProductId, _inStock))
End Sub

End Class

Public Class ProductStockCha ngedEventArgs
Inherits EventArgs

' Instance data for the event args
Dim _inStock As Integer
Dim _productId As Integer

Sub New(ByVal productId As Integer, _
ByVal inStock As Integer)
_inStock = inStock
_productId = productId
End Sub

Public ReadOnly Property InStock() As Integer
Get
Return _inStock
End Get
End Property

Public ReadOnly Property ProductId() As Integer
Get
Return _productId
End Get
End Property
End Class
Module app

' Method to handle the event in the client
Public Sub Notify(ByVal sender As Object, _
ByVal e As ProductStockCha ngedEventArgs)
Console.WriteLi ne( _
"The inventory level for product ID " & _
e.ProductId.ToS tring() & " is now " & _
e.InStock.ToStr ing())
End Sub

Sub Main()

' Create a new product
Dim p As New Product(1)

' Register the handler
Dim p1 As New _
Product.Product StockChangedHan dler( _
AddressOf Notify)
AddHandler p.ProductStockC hanged, p1

' Note that VB allows the previous
' syntax to be shortcutted as:
'AddHandler p.ProductStockC hanged, _
AddressOf Notify

' Make the change
p.InStock = 15

' Dynamically unregister the handler
RemoveHandler p.ProductStockC hanged, _
AddressOf Notify

End Sub

End ModuleVB .NET . Implement the Event Pattern
Listing 1. This simple example implements the .NET Framework Event
Pattern that's based on the Observer pattern. In this example the Product
class declares a Delegate that's used to define the signature of an event
fired when the number of items in stock changes. The client (Observer) can
then create a new Delegate object and dynamically bind it to the event fired
by the Product. The common language runtime handles the notification of the
observers by invoking the Delegate when the RaiseEvent statement executes.
In this case, VB.NET includes the Delegate, Event, RaiseEvent, AddHandler,
and RemoveHandler keywords to work with Delegates, while C# includes the
Delegate and event keywords.
Public Class Product

' Delegate to represent the event
Delegate Sub ProductStockCha ngedHandler( _
ByVal sender As Object, _
ByVal e As ProductStockCha ngedEventArgs)
' Declare an event that uses the delegate
Public Event ProductStockCha nged As _
ProductStockCha ngedHandler

' Instance data for a product
Dim _inStock As Integer
Dim _productId As Integer

Public Sub New(ByVal productId As Integer)
_productId = productId
End Sub

Public Property ProductId() As Integer
Get
Return _productId
End Get
Set(ByVal Value As Integer)
_productId = Value
End Set
End Property

Public Property InStock() As Integer
Get
Return _inStock
End Get
Set(ByVal Value As Integer)
_inStock = Value
' Call the protected method to fire the event
OnProductStockC hanged()
End Set
End Property

' Method used to fire the event
Protected Sub OnProductStockC hanged()
RaiseEvent ProductStockCha nged(Me, _
New ProductStockCha ngedEventArgs( _
Me.ProductId, _inStock))
End Sub

End Class

Public Class ProductStockCha ngedEventArgs
Inherits EventArgs

' Instance data for the event args
Dim _inStock As Integer
Dim _productId As Integer

Sub New(ByVal productId As Integer, _
ByVal inStock As Integer)
_inStock = inStock
_productId = productId
End Sub

Public ReadOnly Property InStock() As Integer
Get
Return _inStock
End Get
End Property

Public ReadOnly Property ProductId() As Integer
Get
Return _productId
End Get
End Property
End Class
Module app

' Method to handle the event in the client
Public Sub Notify(ByVal sender As Object, _
ByVal e As ProductStockCha ngedEventArgs)
Console.WriteLi ne( _
"The inventory level for product ID " & _
e.ProductId.ToS tring() & " is now " & _
e.InStock.ToStr ing())
End Sub

Sub Main()

' Create a new product
Dim p As New Product(1)

' Register the handler
Dim p1 As New _
Product.Product StockChangedHan dler( _
AddressOf Notify)
AddHandler p.ProductStockC hanged, p1

' Note that VB allows the previous
' syntax to be shortcutted as:
'AddHandler p.ProductStockC hanged, _
AddressOf Notify

' Make the change
p.InStock = 15

' Dynamically unregister the handler
RemoveHandler p.ProductStockC hanged, _
AddressOf Notify

End Sub

End Module
Jul 19 '05 #1
0 7020

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1355
by: Paolino | last post by:
Lately I was needing to use multiple inheritance to split behaviour of a class and modularize it. But the problem raises when the need is to add operations to a method already present in one of them from another. I think the technical solution is the use of 'super'. Then I tried to write a decorator for automatize the 'super' call,but I...
3
2618
by: Michael Schneider | last post by:
Hello All, I am comming back to python after being away for several years. I would like to use weak refs in an observer pattern implementation. The problme that I have seems to be that weakrefs can't manage functions. ------------------- from docs: http://www.python.org/doc/current/lib/module-weakref.html
4
1923
by: decrypted | last post by:
Since I couldn't find a OO design/architext forum, I thought I would post here... I have a win app with forms management. forms are grouped by category (pertains to company, pertains to project. etc). This is represented, for example, by a company window containing additional windows such as company information, document history, yada yada....
0
332
by: Andy Read | last post by:
Hello all, I have the requirement to produce source code that produces an object hierarchy. Example: Root | Folder 1
0
1615
by: FluffyCat | last post by:
Last week I continued my series of design patterns examples using PHP 5. Here now is my 14th example, the Observer pattern. http://www.fluffycat.com/PHP-Design-Patterns-Observer/ In the Observer Pattern, a Subject object notifies an Observer object if it's the Subject object's state changes. Pretty simple and fairly useful.
22
4698
by: Krivenok Dmitry | last post by:
Hello All! I am trying to implement my own Design Patterns Library. I have read the following documentation about Observer Pattern: 1) Design Patterns by GoF Classic description of Observer. Also describes implementation via ChangeManager (Mediator + Singleton) 2) Pattern hatching by John Vlissides Describes Observer's implementation via...
1
1865
by: Christopher | last post by:
The observer pattern itself is easy enough. I've implemented it using a Event that contains data for any Event type I forsee my application using. My problem is I don't want one and only one general purpose type of Event. I want to write my design in such a way that more Event Types can be created and used down the road as needed. How can you...
4
2106
by: Mohamed Mansour | last post by:
Hello, What is the purpose of implementing the Observer Pattern if we can trigger an event easily? For example (from books), You have a "Forecaster" which notifies "Observable" when a prediction is ready, then there is a "WeatherViewer" which calls methods from the "Observer Interface".
5
1468
by: Alan Isaac | last post by:
I have two questions about the "observer pattern" in Python. This is question #1. (I'll put the other is a separate post.) Here is a standard example of the observer pattern in Python:
0
7568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7492
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7852
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6109
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5133
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3537
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3525
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1990
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
808
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.