.Net framework 4.0 is going to come up with two new interfaces IObservable and IObserver. These interfaces is going to give a cleaner way to implement observer pattern in your code. In observer design pattern there are two parties involved. One is observer and another is subject.The subject maintains a list of observers and notifies them in case of change in its state.
In .net framework 4 the implementation of observer pattern can be achieved by implementing two interfaces IObservable and IObserver. The class implementing IObservable plays the role of subject and the class implemeniting IObserver acts as observer.
Let us assume that a 'Blog' has some subscribers who want to be notified after every article posted in the 'Blog'. So we can say that here the readers are subscribers to the 'Blog' and they are observer. On the other hand 'Blog' is the subject or observable. When a new article is posted in the blog subscriber will be notified about the article. The following block of codes will help you to understand you can implement this in .net framework 4.0 with two new interfaces.
namespace ObserverExample
{
class Program
{
static void Main(string[] args)
{
Blog blog = new Blog();
/***********Subscribe to the blog********/
blog.Subscribe(new Subscriber { Name = "Alex" , Email="alex@abc.com"});
blog.Subscribe(new Subscriber { Name = "Kevin", Email = "kevin@abc.com" });
blog.Subscribe(new Subscriber { Name = "Kelly", Email="kelly@mail.com"});
blog.PostArticle();
Console.ReadLine();
}
}
public class Article
{
public string Title
{
get;
set;
}
public string Content
{
get;
set;
}
public string Url
{
get;
set;
}
}
public class Blog : IObservable<Article>
{
List<IObserver<Article>> observers = new List<IObserver<Article>>();
Article _article;
#region IObservable<user> Members
public IDisposable Subscribe(IObserver<Article> observer)
{
observers.Add(observer);
return observer as IDisposable;
}
#endregion
public void PostArticle()
{
_article = new Article { Content="Cleaner way to implement observer", Title="Observer pattern in .net 4.0", Url="http://observer.blog.com"};
/*********Save article and then notify observers*****************/
foreach (IObserver<article> observer in observers)
{
observer.OnNext(_article);
}
}
}
public class Subscriber : IObserver<Article>
{
#region IObserver<Article> Members
public string Name
{
get;
set;
}
public string Email
{
get;
set;
}
public void OnCompleted()
{
Console.WriteLine("Finished sending notification.");
}
public void OnError(Exception error)
{
Console.WriteLine("Error sending notification");
}
/****************This is the function which will be called to notify observer***************/
public void OnNext(Article value)
{
/*************Writing to console****************/
/************You should write code here according to your notification mechanism to the subscriber/observer ************/
Console.WriteLine("Name:{0} Email:{1}", this.Name, this.Email);
Console.WriteLine("Title:{0}\n Content:{1}", value.Title,value.Content);
}
#endregion
}
}
Though the example is trivial I hope this one will help anyone to understand how to implement observer pattern in a cleaner way in framewok 4.0.
{
class Program
{
static void Main(string[] args)
{
Blog blog = new Blog();
/***********Subscribe to the blog********/
blog.Subscribe(new Subscriber { Name = "Alex" , Email="alex@abc.com"});
blog.Subscribe(new Subscriber { Name = "Kevin", Email = "kevin@abc.com" });
blog.Subscribe(new Subscriber { Name = "Kelly", Email="kelly@mail.com"});
blog.PostArticle();
Console.ReadLine();
}
}
public class Article
{
public string Title
{
get;
set;
}
public string Content
{
get;
set;
}
public string Url
{
get;
set;
}
}
public class Blog : IObservable<Article>
{
List<IObserver<Article>> observers = new List<IObserver<Article>>();
Article _article;
#region IObservable<user> Members
public IDisposable Subscribe(IObserver<Article> observer)
{
observers.Add(observer);
return observer as IDisposable;
}
#endregion
public void PostArticle()
{
_article = new Article { Content="Cleaner way to implement observer", Title="Observer pattern in .net 4.0", Url="http://observer.blog.com"};
/*********Save article and then notify observers*****************/
foreach (IObserver<article> observer in observers)
{
observer.OnNext(_article);
}
}
}
public class Subscriber : IObserver<Article>
{
#region IObserver<Article> Members
public string Name
{
get;
set;
}
public string Email
{
get;
set;
}
public void OnCompleted()
{
Console.WriteLine("Finished sending notification.");
}
public void OnError(Exception error)
{
Console.WriteLine("Error sending notification");
}
/****************This is the function which will be called to notify observer***************/
public void OnNext(Article value)
{
/*************Writing to console****************/
/************You should write code here according to your notification mechanism to the subscriber/observer ************/
Console.WriteLine("Name:{0} Email:{1}", this.Name, this.Email);
Console.WriteLine("Title:{0}\n Content:{1}", value.Title,value.Content);
}
#endregion
}
}
Though the example is trivial I hope this one will help anyone to understand how to implement observer pattern in a cleaner way in framewok 4.0.
Good article but it would be better if you used code syntax highlighter.
ReplyDeleteI do not even know how I ended up here, but I thought
ReplyDeletethis post was great. I don't know who you are but definitely you're going to a famous blogger
if you are not already ;) Cheers!
Feel free to surf to my web blog: entrepreneur ideas for students
Hello would you mind sharing which blog platform you're working with? I'm going to start my
ReplyDeleteown blog soon but I'm having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I'm looking for something
unique. P.S My apologies for being off-topic but I had to
ask!
Feel free to surf to my site; pay per click search engine marketing
Just wish to say your article is as astonishing.
ReplyDeleteThe clarity in your post is just great and i can assume you are an expert on this subject.
Fine with your permission allow me to grab your feed to keep updated with forthcoming post.
Thanks a million and please carry on the
enjoyable work.
My website ... firmenkonto trotz schufa
Good post! We are linking to this particularly great content on our site.
ReplyDeleteKeep up the great writing.
Check out my webpage: private krankenversicherung studententarif
Greetings, I believe your web site might be having internet browser compatibility issues.
ReplyDeleteWhen I take a look at your web site in Safari, it looks fine but when opening
in IE, it has some overlapping issues. I simply wanted to provide you
with a quick heads up! Other than that, wonderful site!
Check out my homepage :: kredit ohne schufa erfahrung
Spot on with this write-up, I truly think this website needs a great deal
ReplyDeletemore attention. I'll probably be returning to read through more, thanks for the information!
my blog ... bad credit refinancing home loan
I could not refrain from commenting. Very well written!
ReplyDeleteFeel free to surf to my web site ... http://nrec.neurologie.uni-tuebingen.de/nrec/SerenaJdf
Also see my web site - http://www.moveyourmoneyproject.org/node/10806/
I love reading through a post that can make people think.
ReplyDeleteAlso, thanks for allowing me to comment!
Feel free to surf to my page products affiliate
I love reading through a post that can make people
ReplyDeletethink. Also, thanks for allowing me to comment!
Feel free to surf to my blog products affiliate
my site :: the best affiliate program
Why people still make use of to read news papers when in this technological world everything
ReplyDeleteis accessible on web?
my web blog; private krankenversicherung sinnvoll
My family members all the time say that I am killing my time here at
ReplyDeletenet, but I know I am getting familiarity daily by reading such pleasant articles or reviews.
My blog: test krankenkasse
My page: gesetzliche krankenversicherung vergleich stiftung warentest
That is very fascinating, You are a very professional blogger.
ReplyDeleteI've joined your rss feed and sit up for looking for extra of your wonderful post. Also, I have shared your web site in my social networks
Take a look at my page: can someone with bad credit buy a house
Hi, every time i used to check web site posts here early in the morning, for the reason that i like to gain knowledge of more and more.
ReplyDeleteFeel free to visit my blog :: best honeymoon destinations
Why users still use to read news papers when in this technological globe everything is presented on net?
ReplyDeleteAlso visit my web page ... search engine optimization top
Fastidious replies in return of this difficulty with firm arguments and telling all
ReplyDeleteconcerning that.
My website :: paid surveys
my page > promote products online
What's up to all, how is all, I think every one is getting more from this web site, and your views are pleasant for new visitors.
ReplyDeleteAlso visit my site: private Krankenversicherung gesetzliche krankenversicherung
Actually when someone doesn't be aware of afterward its up to other visitors that they will help, so here it happens.
ReplyDeleteMy web blog :: starting A business idea
Also see my page - business new ideas
My programmer is trying to persuade me to move to .net
ReplyDeletefrom PHP. I have always disliked the idea because of the costs.
But he's tryiong none the less. I've been using Movable-type on various websites for about a year and
am nervous about switching to another platform. I have heard
excellent things about blogengine.net. Is there a way
I can import all my wordpress content into it?
Any help would be greatly appreciated!
my blog; billige online shops kleidung
my web page > Designer Outlet Online Shop
It's an amazing paragraph designed for all the online users; they will obtain advantage from it I am sure.
ReplyDeleteMy page does clickbank work
Hello everybody, here every person is sharing these knowledge, therefore it's pleasant to read this website, and I used to visit this blog everyday.
ReplyDeleteHere is my blog post; mom jobs
Usually I do not learn post on blogs, however I wish to say
ReplyDeletethat this write-up very compelled me to take a look at and do
so! Your writing style has been amazed me. Thank you, very great
post.
Also visit my page :: home loans bad credit score
We're a group of volunteers and starting a new scheme in our community. Your web site provided us with valuable info to work on. You have done an impressive job and our whole community will be grateful to you.
ReplyDeleteAlso visit my web page ... Best Reseller Hosting Review
Good day! I know this is somewhat off topic but I was wondering if you knew
ReplyDeletewhere I could get a captcha plugin for my comment form? I'm using the same blog platform as yours and I'm having problems finding one?
Thanks a lot!
Also visit my web blog: earn money as an affiliate
It's an remarkable post for all the web users; they will obtain advantage from it I am sure.
ReplyDeleteHere is my blog: Http://www.businessdirectory.bz/user_detail.php?u=malinda84
Very nice article, just what I was looking for.
ReplyDeleteAlso visit my webpage; wechsel private kv in gesetzliche kv
Hmm it appears like your website ate my first comment (it was super long) so I guess I'll just sum it up what I wrote and say, I'm thoroughly enjoying your
ReplyDeleteblog. I too am an aspiring blog blogger but I'm still new to everything. Do you have any tips for first-time blog writers? I'd really appreciate it.
Also visit my page: top web hosting companies
This page definitely has all the information I wanted about this subject
ReplyDeleteand didn't know who to ask.
my web blog: your own business ideas
This is my first time visit at here and i am in fact impressed to
ReplyDeleteread all at alone place.
My web blog Student Private krankenversicherung
Good day! This is my 1st comment here so I just wanted to give
ReplyDeletea quick shout out and say I really enjoy reading your posts.
Can you suggest any other blogs/websites/forums that
go over the same subjects? Thank you!
Visit my web site ... reseller panel
I’m not that much of a internet reader to be honest but your sites really nice, keep it up!
ReplyDeleteI'll go ahead and bookmark your site to come back in the future. Cheers
My weblog; What can home equity loans be used for
Thanks for one's marvelous posting! I certainly enjoyed reading it, you are a great author. I will remember to bookmark your blog and will come back in the future. I want to encourage you continue your great job, have a nice morning!
ReplyDeleteFeel free to surf to my web page :: günstig schuhe online
I am in fact delighted to read this web site posts which
ReplyDeletecarries tons of useful facts, thanks for providing such information.
Feel free to visit my web-site private studenten Krankenversicherung
An outstanding share! I've just forwarded this onto a co-worker who has been conducting a little homework on this. And he actually bought me dinner simply because I discovered it for him... lol. So let me reword this.... Thank YOU for the meal!! But yeah, thanks for spending the time to discuss this topic here on your site.
ReplyDeleteCheck out my weblog best place to get private student loans
Сuггently it ѕeems lіke Expression
ReplyDeleteEngine іѕ the toρ blogging рlatform aνailаble right now.
(from what І've read) Is that what you are using on your blog?
Stop by my page ... DiamondLinks