Observer Design Pattern
page 3 of 5
by Vishal Patil
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 22814/ 18

.NET Framework examples

There are many instances of Observer design pattern implementation in .NET Framework.  A few of the .NET Framework classes which implement Observer design pattern are DefaultTraceListener, TextWriterTraceListener and EventLogTraceListener.  Adding these Listeners to the Listenerscollection of Trace object allows us to receive notifications and then consume them.  Below is an example that demonstrates the TextWriterTraceListener class.

Listing 1

TextWriterTraceListener listener = newTextWriterTraceListener("c:\\Myfile.txt");
Trace.AutoFlush = true;

In the above code listing, a TextWriterTraceListener is added to the listener's collection of Trace objects.  This TextWriterTraceListener collects the output from the trace statements and writes messages to an instance of a Stream class, including output to the text file.

Next, Autoflush property is set to true, which allows Trace object to write to the output buffer and causes output buffered data to be written to the listener after every write.

In this example, we have seen that Listener acts as publisher while it maintains the output from the trace statement and notifies to the text file (Subscriber).

Another example in .NET Framework can be Cache dependency.

In the Cache dependency concept, Cache item validity will depend on the external file or on another cache item.  If a dependency changes, the cache item is invalidated and removed from the cache.  For example, Suppose XML file contains data from which an application reads data and processes and draws different views of graphs.  In such scenarios, applications cache data and will create dependencies on the file from which the data will be read.  Whenever this XML file is updated, Cache data will be removed and the application will reread data and insert again the updated copy of the latest data into the cache.

View Entire Article

User Comments

Title: Easy to understand   
Name: Vijay
Date: 2007-06-01 9:16:14 AM

I have browsed for many articles in the net and your articles on design patterns are really simple and easy to understand. Your work on this is really appreciated.

Title: Good article   
Name: Vikram
Date: 2006-06-29 4:46:34 AM
Nice article.. Vishal. written in very simple language and the use of non software examples make it very easy to grasp the fundamentals behind the pattern.great goin.. more articles on design patterns would be higly appreciated.

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-04-15 6:17:50 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search