TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Observer Pattern
Aankur Singla
Aug 03
2016
Code
911
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
public
class
Subject
{
List<IObserver> _subjects =
new
List<IObserver>();
string
_message =
string
.Empty;
public
void
Subscribe(IObserver Subject)
{
_subjects.Add(Subject);
}
private
void
NotifySubscriber()
{
_subjects.ForEach(subject => subject.UpdateState());
}
public
string
GetMessage()
{
return
_message;
}
public
void
SetMessage(
string
Message)
{
_message = Message;
NotifySubscriber();
}
}
public
interface
IObserver
{
Subject subject {
get
;
set
; }
void
UpdateState();
}
public
class
Subscriber1 : IObserver
{
public
Subscriber1(Subject OSubject)
{
this
.subject = OSubject;
this
.subject.Subscribe(
this
);
}
public
Subject subject {
get
;
set
; }
public
void
UpdateState()
{
Console.WriteLine(
"Subscriber 1 is notified with value: "
+ subject.GetMessage());
}
}
public
class
Subscriber2 : IObserver
{
public
Subscriber2(Subject OSubject)
{
this
.subject = OSubject;
this
.subject.Subscribe(
this
);
}
public
Subject subject {
get
;
set
; }
public
void
UpdateState()
{
Console.WriteLine(
"Subscriber 2 is notified with value: "
+ subject.GetMessage());
}
}
//Consume Observer pattern
Subject oSubject =
new
Subject();
Subscriber1 osub1 =
new
Subscriber1(oSubject);
Subscriber2 osub2 =
new
Subscriber2(oSubject);
Console.WriteLine(
"====This is a test message 1===="
);
oSubject.SetMessage(
"First message from Subject"
);
Console.WriteLine(
"====This is a test message 2===="
);
oSubject.SetMessage(
"Second message from Subject"
);
Console.ReadLine();
C#