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.Listeners.Add(listener);
Trace.AutoFlush = true;
Trace.Write("Hi");
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.