Tuesday, July 21, 2009

Observer Design Pattern in C#

Introduction

The Observer design pattern is a relationship between objects so that when one
changes its state, all the others are notified accordingly. In other words it defines that an object must be able to notify other objects without making assumptions about what these objects are.

Observer design pattern is quite useful when a change to one object requires changing others but, you don't know how many objects need to be changed.

Using Observer Design Pattern in Blog Subscriber Example.

In this example i have used two other behavioral patterns which are Iterator Design Pattern in C# and Facade Design Pattern in C#. The simplest way to understand observer pattern is to look at blogs, which are website where people write about different topics. Take a example of a one blog where so many users have subscribed themselves for any new post. As we all know bloggers don't always post regularly so it would be great for bloggers to alert his all subscribers whenever blogger post a new topic.

Blog is a class which deals with the new blog post and also with the blog subscribers.
BlogPost is a class which deals with the posting of new article.
Subscribers are the user who have subscribed themselves for alerts of new articles.
Facade deals them in simpler way and give you operations like PublishSinglePost() or PublishMultiPost() etc.
Subject class whose instances independently change their state and it notify to all the subscribers. Run method loops through all of the Subscribers calling their Update methods to notify them about post. Its also contains methods for attaching and detaching functions with event

Imagine using Iterator Design Pattern in C# we have a list of subscriber as follows.


See full detail: http://www.codeproject.com/Articles/38188/Encrypt-Your-Web-config-Please.aspx

No comments: