Observer Design Pattern
Making Publisher Subscriber in Sync
Sameer Singh Rathoud
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.
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
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
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()
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()
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;
}
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.
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”.
Solution
UpdateNewsOnWeb
Update()
BroadcastNewsOnSMS
Update()
BroadcastNewsOnChannel
Update()
<<interface>>
BroadcastMechanism
Update()
<<interface>>
FakingNews
AddBroadcastMechanism(Broadcast
Mechanism)
RemoveBroadcastMechanism(Broad
castMechanism)
+ Notify()
FackingNews
Concrete3
List<BroadcastMechanism>
RegisteredBM
FackingNews
Concrete2
FackingNews
Concrete1
Here 3 concrete classes are implementing
“FackingNews” interface and these concrete
classes can be considered as the updates coming
from various news reporters. And as soon as the
news is reported by any reporters. The
“FackingNews.Notify()” all its registered
broadcastMechanism.
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.
Structure
Inheritance
<< interface >>
Subject
AddObserver()
RemoveObserver()
Notify()
ConcreteSubject1
GetState()
SetState()
SubjectState
ConcreteSubject2
GetState()
SetState()
SubjectState
<< interface >>
Observer
Update()
ConcreteObserver1
Update()
Container<Observer>
foreach(o in observer)
o.Update()
ConcreteObserver2
Update()
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
Collaborations
• Subject notify all the attached observer on change of state.
ConcreteSubject ConcreteObserver1 ConcreteObserver2
Update()
SetState()SetState()
Notify()
Update()
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
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.
Implementation (C#)
ConcreteObserver
class UpdateNewsOnTV : BroadcastMechanism {
public UpdateNewsOnTV(FakingNews fn) {
fnObj = fn;
}
public override void Update()
{
System.Console.WriteLine("On TV: {0}",
fnObj.UpdatedNews);
}
};
FakingNews fnObj
<< interface >> BroadcastMechanism
Update()
UpdateNewsOnSMS(FakingNews fn)
UpdateNewsOnSMS
Update()
UpdateNewsOnWeb(FakingNews fn)
Update()
UpdateNewsOnWeb
UpdateNewsOnTV(FakingNews fn)
Update()
UpdateNewsOnTV
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
Implementation (C#)
Subject (Interface)
<< interface >> FakingNews
void AddBM(BroadcastMechanism)
void RemoveBM(BroadcastMechanism)
void Notify()
void GetUpdated(String)
+ string UpdatedNews
- List<BroadcastMechanism>
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)
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())
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.
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.
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.
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.
End of Presentation . . .

More Related Content

PPTX
Observer pattern
PDF
Observer Pattern
PPT
Observer Pattern Khali Young 2006 Aug
PDF
Observer Pattern
PPT
Observer and Decorator Pattern
PPSX
Observer design pattern
ODP
Design Pattern - 2. Observer
PPT
Design patterns - Observer Pattern
Observer pattern
Observer Pattern
Observer Pattern Khali Young 2006 Aug
Observer Pattern
Observer and Decorator Pattern
Observer design pattern
Design Pattern - 2. Observer
Design patterns - Observer Pattern

What's hot (12)

PPTX
Design Pattern - Observer Pattern
PPT
Observer pattern
PPTX
Observer pattern
PPT
Ext Js Events
PDF
RxJava pour Android : présentation lors du GDG Android Montréal
DOCX
ECET 370 Exceptional Education - snaptutorial.com
PDF
Parameter Estimation User Guide
PDF
MySQL Manchester TT - JSON Example
PDF
Triggers and active database
PPT
Unit 6 Java
PPT
Realizing an Application Use Case
DOC
New Microsoft Word Document.doc
Design Pattern - Observer Pattern
Observer pattern
Observer pattern
Ext Js Events
RxJava pour Android : présentation lors du GDG Android Montréal
ECET 370 Exceptional Education - snaptutorial.com
Parameter Estimation User Guide
MySQL Manchester TT - JSON Example
Triggers and active database
Unit 6 Java
Realizing an Application Use Case
New Microsoft Word Document.doc
Ad

Viewers also liked (16)

PPTX
Design pattern - Software Engineering
PPTX
Design patterns
PPTX
Konstantin slisenko - Design patterns
PPTX
Design pattern-presentation
PDF
L05 Design Patterns
PPTX
Observation Method
PPTX
Observer Software Design Pattern
PPTX
Observer design pattern
PPTX
Observer pattern, delegate, event, lambda expression
PPTX
Design patterns
PDF
The Observer Pattern (Definition using UML)
PPTX
Observer & singleton pattern
PDF
Observer pattern
PPT
Design patterns 4 - observer pattern
PDF
Design Patterns
PPTX
Design patterns: observer pattern
Design pattern - Software Engineering
Design patterns
Konstantin slisenko - Design patterns
Design pattern-presentation
L05 Design Patterns
Observation Method
Observer Software Design Pattern
Observer design pattern
Observer pattern, delegate, event, lambda expression
Design patterns
The Observer Pattern (Definition using UML)
Observer & singleton pattern
Observer pattern
Design patterns 4 - observer pattern
Design Patterns
Design patterns: observer pattern
Ad

Similar to Observer design pattern (20)

PPTX
Implementation of Push Notification in React Native Android app using Firebas...
PDF
Writing native Mac apps in C# with Xamarin.Mac - Aaron Bockover
PDF
GNURAdioDoc-8
PDF
GNURAdioDoc-8
PDF
Roboconf Detailed Presentation
PPT
Maf Event Bus
DOCX
Backtrack Manual Part6
ODP
Emulink: Simulink environment for PVS
PDF
Android development training programme , Day 3
PPT
WPF Windows Presentation Foundation A detailed overview Version1.2
PPTX
How to Setup Real-Time Communication in odoo_ Using the Bus Service
DOCX
Dynamic autoselection and autotuning of machine learning models forcloud netw...
PDF
IBM MobileFirst Platform v7.0 POT App Mgmt Lab v1.1
PDF
Managing multi-version applications in cics
PPTX
Android Application Component: BroadcastReceiver Tutorial
PPTX
Making flow Mule
DOC
User's Guide
PDF
Ax2012 technical Upgrade process
PPTX
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
PPTX
AdvancedJava.pptx
Implementation of Push Notification in React Native Android app using Firebas...
Writing native Mac apps in C# with Xamarin.Mac - Aaron Bockover
GNURAdioDoc-8
GNURAdioDoc-8
Roboconf Detailed Presentation
Maf Event Bus
Backtrack Manual Part6
Emulink: Simulink environment for PVS
Android development training programme , Day 3
WPF Windows Presentation Foundation A detailed overview Version1.2
How to Setup Real-Time Communication in odoo_ Using the Bus Service
Dynamic autoselection and autotuning of machine learning models forcloud netw...
IBM MobileFirst Platform v7.0 POT App Mgmt Lab v1.1
Managing multi-version applications in cics
Android Application Component: BroadcastReceiver Tutorial
Making flow Mule
User's Guide
Ax2012 technical Upgrade process
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
AdvancedJava.pptx

More from Sameer Rathoud (8)

PDF
Platformonomics
PDF
AreWePreparedForIoT
PDF
Decorator design pattern (A Gift Wrapper)
PDF
Memory Management C++ (Peeling operator new() and delete())
PDF
Proxy design pattern (Class Ambassador)
PDF
Builder Design Pattern (Generic Construction -Different Representation)
PDF
Factory method pattern (Virtual Constructor)
PPTX
Singleton Pattern (Sole Object with Global Access)
Platformonomics
AreWePreparedForIoT
Decorator design pattern (A Gift Wrapper)
Memory Management C++ (Peeling operator new() and delete())
Proxy design pattern (Class Ambassador)
Builder Design Pattern (Generic Construction -Different Representation)
Factory method pattern (Virtual Constructor)
Singleton Pattern (Sole Object with Global Access)

Recently uploaded (20)

PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
OpenACC and Open Hackathons Monthly Highlights July 2025
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
STKI Israel Market Study 2025 version august
PDF
sbt 2.0: go big (Scala Days 2025 edition)
PDF
Developing a website for English-speaking practice to English as a foreign la...
PPTX
Microsoft Excel 365/2024 Beginner's training
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PDF
CloudStack 4.21: First Look Webinar slides
PDF
Credit Without Borders: AI and Financial Inclusion in Bangladesh
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Five Habits of High-Impact Board Members
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PPT
Module 1.ppt Iot fundamentals and Architecture
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
A comparative study of natural language inference in Swahili using monolingua...
OpenACC and Open Hackathons Monthly Highlights July 2025
Hindi spoken digit analysis for native and non-native speakers
sustainability-14-14877-v2.pddhzftheheeeee
STKI Israel Market Study 2025 version august
sbt 2.0: go big (Scala Days 2025 edition)
Developing a website for English-speaking practice to English as a foreign la...
Microsoft Excel 365/2024 Beginner's training
The influence of sentiment analysis in enhancing early warning system model f...
CloudStack 4.21: First Look Webinar slides
Credit Without Borders: AI and Financial Inclusion in Bangladesh
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Five Habits of High-Impact Board Members
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
A contest of sentiment analysis: k-nearest neighbor versus neural network
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
Custom Battery Pack Design Considerations for Performance and Safety
Module 1.ppt Iot fundamentals and Architecture
Consumable AI The What, Why & How for Small Teams.pdf
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor

Observer design pattern

  • 1. Observer Design Pattern Making Publisher Subscriber in Sync Sameer Singh Rathoud
  • 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”.
  • 10. Solution UpdateNewsOnWeb Update() BroadcastNewsOnSMS Update() BroadcastNewsOnChannel Update() <<interface>> BroadcastMechanism Update() <<interface>> FakingNews AddBroadcastMechanism(Broadcast Mechanism) RemoveBroadcastMechanism(Broad castMechanism) + Notify() FackingNews Concrete3 List<BroadcastMechanism> RegisteredBM FackingNews Concrete2 FackingNews Concrete1 Here 3 concrete classes are implementing “FackingNews” interface and these concrete classes can be considered as the updates coming from various news reporters. And as soon as the news is reported by any reporters. The “FackingNews.Notify()” all its 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.
  • 12. Structure Inheritance << interface >> Subject AddObserver() RemoveObserver() Notify() ConcreteSubject1 GetState() SetState() SubjectState ConcreteSubject2 GetState() SetState() SubjectState << interface >> Observer Update() ConcreteObserver1 Update() Container<Observer> foreach(o in observer) o.Update() ConcreteObserver2 Update()
  • 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.
  • 17. Implementation (C#) ConcreteObserver class UpdateNewsOnTV : BroadcastMechanism { public UpdateNewsOnTV(FakingNews fn) { fnObj = fn; } public override void Update() { System.Console.WriteLine("On TV: {0}", fnObj.UpdatedNews); } }; FakingNews fnObj << interface >> BroadcastMechanism Update() UpdateNewsOnSMS(FakingNews fn) UpdateNewsOnSMS Update() UpdateNewsOnWeb(FakingNews fn) Update() UpdateNewsOnWeb UpdateNewsOnTV(FakingNews fn) Update() UpdateNewsOnTV
  • 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
  • 19. Implementation (C#) Subject (Interface) << interface >> FakingNews void AddBM(BroadcastMechanism) void RemoveBM(BroadcastMechanism) void Notify() void GetUpdated(String) + string UpdatedNews - List<BroadcastMechanism>
  • 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.