The document discusses the observer design pattern. It defines the observer pattern as a design where a subject maintains a list of dependent observers and notifies them automatically of any state changes. It then provides an example problem of a news broadcasting company, FakingNews, that needs to update subscribers through different mechanisms. This is solved using the observer pattern by having FakingNews be the subject and the different broadcasting mechanisms (web, SMS, TV) be observers. The implementation in C# code is also outlined, showing interfaces for the subject and observers, and concrete classes for the subject, observers, and a client.
2. About presentation
This presentation provide information to understand observer design pattern, it’s
structure and it’s implementation.
I have tried my best to explain the concept in very simple language.
The programming language used for implementation is c#. But any one from
different programming background can easily understand the implementation.
3. Definition
The observer pattern is a software design pattern in which an object, called the
subject, maintains a list of its dependents, called observers, and notifies them
automatically of any state changes, usually by calling one of their methods
Observer pattern is a behavioral design pattern.
http://en.wikipedia.org/wiki/Observer_pattern
4. Problem
“Faking News” is in the business of news broadcasting. They update there readers/viewers either by
broadcasting there news on faking news channel or by updating the news on there web portal or by
broadcasting the news as short messaging services on the mobiles of there subscribers.
Faking News
5. Problem This is a class structure for our Faking
News where the class gets update from
various reporters (whenever this class is
having some updates from there reporters
operation Update() gets called) and
“FakingNews” class holds the reference of
all the three classes responsible for
updating the news. Inside the body of
operation Update() we give the call to
three operations UpdateNewsChannel(),
UpdateWeb() and UpdateSMSBroadcast()
which are responsible for updating the
respective class for news broadcasting.
FakingNews
Update ()
Reporters
Reporters
Reporters
BroadcastNewsOnChannel
UpdateNewsOnWebBroadcastNewsOnSMS
Update()
- UpdateNewsOnWeb web
- BroadcastNewsOnSMS sms
- BroadcastNewsOnChannel ch
Web.UpdateNewsChannel()
Sms.UpdateWeb()
Ch.UpdateSMSBroadcast()
6. Problem • UpdateNewsChannel(): will update a
class which is responsible for
broadcasting the news on channel.
• UpdateWeb(): will update a class which
is responsible for updating the news on
web portal.
• UpdateSMSBroadcast(): will update a
class “BroadcastNewsOnSMS” with
latest news which is responsible for
broadcasting the news through SMS on
the mobile of there readers. This class
is having the list of register readers
with there mobile numbers.
FakingNews
Update ()
Reporters
Reporters
Reporters
BroadcastNewsOnChannel
UpdateNewsOnWebBroadcastNewsOnSMS
Update()
- UpdateNewsOnWeb web
- BroadcastNewsOnSMS sms
- BroadcastNewsOnChannel ch
Web.UpdateNewsChannel()
Sms.UpdateWeb()
Ch.UpdateSMSBroadcast()
7. Problem: Code
class FakingNews
{
public FakingNews()
{
web = new UpdateNewsOnWeb();
sms = new BroadcastNewsOnSMS();
ch = new BroadcastNewsOnChannel();
}
public void Update()
{
Web.UpdateNewsChannel();
Sms.UpdateWeb();
Ch.UpdateSMSBroadcast();
}
private UpdateNewsOnWeb web;
private BroadcastNewsOnSMS sms;
private BroadcastNewsOnChannel ch;
}
8. Problem
Although this is a workable solution.
But this approach is having some problems:
1) If Faking News wants to add new way to broadcast news to there readers/viewers they have
to give call to a new operation in there Operation Update() to update the class responsible
for new mechanism of broadcast.
2) If Faking News wants to remove a news broadcasting mechanism. They have to remove the
call of the operation of that mechanism.
In both the above mentioned problems FakingNews” class has to get modified and this is
violating open/closed design principle (open for extension and close for modification).
So we to think of some other solution, where we can have a some provision of adding or
removing a news updating mechanism at run-time.
9. Solution
So what we can do to achieve this. We will introduce an interface “BroadcastMechainsm” which
will be having an operation Update() and our classes “UpdateNewsOnWeb”,
“BroadcastNewsOnSMS” and “BroadcastNewsOnChannel” will provide the concrete implementation
to this interface. Our “FakingNews” class will be holding an container of “BroadcastMechanism”
and few operations like “AddBroadcastMechanism()” for registering a new mechanism for news
broadcast, “RemoveBroadcastMechanism()” to unregister already registered broadcast mechanism
and “Notify()” to call Update() of all the registered “BroadcastMechanism”.
11. Motivation and Intent
Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically.
A common side-effect of partitioning a system into a collection of cooperating
classes is the need to maintain consistency between related objects. You don't
want to achieve consistency by making the classes tightly coupled, because that
reduces their reusability.
13. Participants in structure
• Subject (interface):
• Store the list of attached observers and provide operations for adding and removing the
observer objects.
• Expose an operation to notify all the attached observers
• Observer (interface):
• Defines an interface for updating mechanism.
• ConcreteSubject: Get the update either from an external source or from any of the attached
observer and notify the attached observers in case of change state.
• ConcreteObserver:
• Maintains a reference to a ConcreteSubject object.
• Stores state that should stay consistent with the subject's.
• Implements the Observer updating interface to keep its state consistent with the
14. Collaborations
• Subject notify all the attached observer on change of state.
ConcreteSubject ConcreteObserver1 ConcreteObserver2
Update()
SetState()SetState()
Notify()
Update()
15. Implementation (C#)
Observer (Interface)
abstract class BroadcastMechanism {
abstract public void Update();
protected FakingNews fnObj;
};
Here “BroadcastMechanism” is an abstract class
with an abstract method “Update” and a member
variable of class “Faking News”. Now all the
concrete classes implementing this abstract class
will override “Update” method.
<< interface >> BroadcastMechanism
Update()
FakingNews fnObj
16. Implementation (C#)
ConcreteObserver
class UpdateNewsOnWeb: BroadcastMechanism {
public UpdateNewsOnWeb(FakingNews fn) {
fnObj = fn;
}
public override void Update() {
System.Console.WriteLine("On Web: {0}", fnObj.UpdatedNews);
}
};
class UpdateNewsOnSMS : BroadcastMechanism {
public UpdateNewsOnSMS(FakingNews fn) {
fnObj = fn;
}
public override void Update() {
System.Console.WriteLine("On SMS: {0}", fnObj.UpdatedNews);
}
};
Here “UpdateNewsOnWeb”,
“UpdateNewsOnSMS” and
“UpdateNewsOnTV” are few
classes implementing abstract
class “BroadcastMechanism”
and overriding operation
“Update”. These classes are
also defining there constructor
with “FakingNews” object as
a parameter and assigning it to
“FakingNews” object defined
in there base class.
18. Implementation (C#)
Subject (Interface)
abstract class FakingNews {
private List<BroadcastMechanism> BMContainer =
new List<BroadcastMechanism>();
public String UpdatedNews;
public abstract void GetUpdated(String news);
public void AddBM(BroadcastMechanism bm) {
BMContainer.Add(bm);
}
public void RemoveBM(BroadcastMechanism bm) {
BMContainer.Remove(bm);
}
public void Notify() {
foreach (BroadcastMechanism bm in BMContainer) {
bm.Update();
}
}
}
Here “FakingNews” is an abstract class
with an abstract method “GetUpdated”
taking a string argument. This class also
contains below mentioned attributes and
operations:
Attributes:
List<BroadcastMechanism>: container
to store registered
“BroadcastMechanism” objects
string UpdateNews: defines state to
“FakingNews”
Operations:
void AddBM(BroadcastMechanism):
Register a “BroadcastMechanism” object
void RemoveBM(BroadcastMechanism)
Unregister a “BroadcastMechanism”
object
Notify(): call the Update of all the
registered “BroadcastMechanism” object
20. Implementation (C#)
ConcreteSubject:
class FakingNewsReporter1: FakingNews {
public override void GetUpdated(String news)
{
UpdatedNews = news;
}
}
“FakingNewsReporter1” is a concrete
implementation of class “FakingNews” and
overriding “GetUpdated(String)”. This
operation is changing the state of “FakingNews”
class and this change will be notified to all the
registered “BroadcastMechanism” objects.
<< interface >> FakingNews
void AddBM(BroadcastMechanism)
void RemoveBM(BroadcastMechanism)
void Notify()
void GetUpdated(String)
+ string UpdatedNews
- List<BroadcastMechanism>
FakingNewsReporter1
GetUpdated(String)
21. Implementation (C#)
Client
class ObserverDesignPattern {
static void Main(string[] args)
{
FakingNews fn = new FakingNewsReporter1();
BroadcastMechanism bmt = new UpdateNewsOnTV(fn);
fn.AddBM(bmt);
BroadcastMechanism bms = new UpdateNewsOnSMS(fn);
fn.AddBM(bms);
BroadcastMechanism bmw = new UpdateNewsOnWeb(fn);
fn.AddBM(bmw);
fn.GetUpdated("Mosquito diagnosed with lung cancer due to passive smoking");
fn.Notify();
}
}
The client creates the object of
“FakingNewsReporter1”
(ConcerteSubject) and create the
objects of various
“BroadcastMechanism”
(ConcreteObserver) and registering
them to “FakingNews” (by calling
AddBM).
Client Update the news/changing the
state (by calling GetUpdate()) and then
notifying all the registered
“BroadcastMechanism” objects to
update the news (by calling Notify())
22. Example
Auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used to
indicate a bid. The auctioneer starts the bidding, and "observes" when a paddle is raised to accept
the bid. The acceptance of the bid changes the bid price which is broadcast to all of the bidders in
the form of a new bid.
23. Mediator Vs. Observer
Some time people get confused between observer design pattern and mediator design pattern. Here
are some differences between these patterns:
Observer
Defines one to many dependency between
object so that when one object changes state
all its dependent are notified.
Mediator
Define an object that encapsulates how a set
of objects interact. Mediator promotes loose
coupling by keeping objects from referring to
each other explicitly, and it lets you vary
their interaction independently.
24. Mediator Vs. Observer
Observer
In observer pattern a subject can have zero
or more registered observers, when
something is changed in subject all the
registered observers are notified.
Mediator
Let various instances of implementations of
a interface wants to communicate with each
other (but they are not having the direct
references of each other – loosely coupled).
So a mediator class can be introduced and
each instances can have a shared instance of
this mediator class which can help them in
communication.
25. Other patterns which can be used with observer pattern
The Observer pattern is usually used in combination with other design patterns:
1. Factory pattern – A factory method pattern can be used to create the Observers.
2. Template Method - The observer pattern can be used in conjunction with the Template Method
Pattern to make sure that Subject state is self-consistent before notification
3. Mediator Pattern – In case of many subjects and many observers, mediator pattern can be used
to simplify the communication.