SlideShare a Scribd company logo
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
Samreen Farooq
 
PDF
Observer Pattern
Akshat Vig
 
PPT
Observer Pattern Khali Young 2006 Aug
melbournepatterns
 
PDF
Observer Pattern
Anshuman Biswal
 
PPT
Observer and Decorator Pattern
Jonathan Simon
 
PPSX
Observer design pattern
Sara Torkey
 
ODP
Design Pattern - 2. Observer
Francesco Ierna
 
PPT
Design patterns - Observer Pattern
Annamalai Chockalingam
 
Observer pattern
Samreen Farooq
 
Observer Pattern
Akshat Vig
 
Observer Pattern Khali Young 2006 Aug
melbournepatterns
 
Observer Pattern
Anshuman Biswal
 
Observer and Decorator Pattern
Jonathan Simon
 
Observer design pattern
Sara Torkey
 
Design Pattern - 2. Observer
Francesco Ierna
 
Design patterns - Observer Pattern
Annamalai Chockalingam
 

What's hot (12)

PPTX
Design Pattern - Observer Pattern
Mudasir Qazi
 
PPT
Observer pattern
Shakil Ahmed
 
PPTX
Observer pattern
Shahriar Iqbal Chowdhury
 
PPT
Ext Js Events
jason hu 金良胡
 
PDF
RxJava pour Android : présentation lors du GDG Android Montréal
Sidereo
 
DOCX
ECET 370 Exceptional Education - snaptutorial.com
donaldzs157
 
PDF
Parameter Estimation User Guide
Andy Salmon
 
PDF
MySQL Manchester TT - JSON Example
Mark Swarbrick
 
PDF
Triggers and active database
BalaMuruganSamuthira
 
PPT
Unit 6 Java
arnold 7490
 
PPT
Realizing an Application Use Case
Leslie Munday
 
DOC
New Microsoft Word Document.doc
butest
 
Design Pattern - Observer Pattern
Mudasir Qazi
 
Observer pattern
Shakil Ahmed
 
Observer pattern
Shahriar Iqbal Chowdhury
 
Ext Js Events
jason hu 金良胡
 
RxJava pour Android : présentation lors du GDG Android Montréal
Sidereo
 
ECET 370 Exceptional Education - snaptutorial.com
donaldzs157
 
Parameter Estimation User Guide
Andy Salmon
 
MySQL Manchester TT - JSON Example
Mark Swarbrick
 
Triggers and active database
BalaMuruganSamuthira
 
Unit 6 Java
arnold 7490
 
Realizing an Application Use Case
Leslie Munday
 
New Microsoft Word Document.doc
butest
 
Ad

Viewers also liked (16)

PPTX
Design pattern - Software Engineering
Nadimozzaman Pappo
 
PPTX
Design patterns
GeekNightHyderabad
 
PPTX
Konstantin slisenko - Design patterns
beloslab
 
PPTX
Design pattern-presentation
Rana Muhammad Asif
 
PDF
L05 Design Patterns
Ólafur Andri Ragnarsson
 
PPTX
Observation Method
Pamela Bianca Mas
 
PPTX
Observer Software Design Pattern
Nirthika Rajendran
 
PPTX
Observer design pattern
Yenifer Castrillon
 
PPTX
Observer pattern, delegate, event, lambda expression
LearningTech
 
PPTX
Design patterns
ISsoft
 
PDF
The Observer Pattern (Definition using UML)
John Ortiz
 
PPTX
Observer & singleton pattern
babak danyal
 
PDF
Observer pattern
Somenath Mukhopadhyay
 
PPT
Design patterns 4 - observer pattern
pixelblend
 
PDF
Design Patterns
Srikrishnan Suresh
 
PPTX
Design patterns: observer pattern
Jyaasa Technologies
 
Design pattern - Software Engineering
Nadimozzaman Pappo
 
Design patterns
GeekNightHyderabad
 
Konstantin slisenko - Design patterns
beloslab
 
Design pattern-presentation
Rana Muhammad Asif
 
L05 Design Patterns
Ólafur Andri Ragnarsson
 
Observation Method
Pamela Bianca Mas
 
Observer Software Design Pattern
Nirthika Rajendran
 
Observer design pattern
Yenifer Castrillon
 
Observer pattern, delegate, event, lambda expression
LearningTech
 
Design patterns
ISsoft
 
The Observer Pattern (Definition using UML)
John Ortiz
 
Observer & singleton pattern
babak danyal
 
Observer pattern
Somenath Mukhopadhyay
 
Design patterns 4 - observer pattern
pixelblend
 
Design Patterns
Srikrishnan Suresh
 
Design patterns: observer pattern
Jyaasa Technologies
 
Ad

Similar to Observer design pattern (20)

PPTX
Implementation of Push Notification in React Native Android app using Firebas...
naseeb20
 
PDF
Writing native Mac apps in C# with Xamarin.Mac - Aaron Bockover
Xamarin
 
PDF
GNURAdioDoc-8
tutorialsruby
 
PDF
GNURAdioDoc-8
tutorialsruby
 
PDF
Roboconf Detailed Presentation
Vincent Zurczak
 
PPT
Maf Event Bus
Paolo Quadrani
 
DOCX
Backtrack Manual Part6
Nutan Kumar Panda
 
ODP
Emulink: Simulink environment for PVS
edge7
 
PDF
Android development training programme , Day 3
DHIRAJ PRAVIN
 
PPT
WPF Windows Presentation Foundation A detailed overview Version1.2
Shahzad
 
PPTX
How to Setup Real-Time Communication in odoo_ Using the Bus Service
Celine George
 
DOCX
Dynamic autoselection and autotuning of machine learning models forcloud netw...
Venkat Projects
 
PDF
IBM MobileFirst Platform v7.0 POT App Mgmt Lab v1.1
Banking at Ho Chi Minh city
 
PDF
Managing multi-version applications in cics
Matthew Webster
 
PPTX
Android Application Component: BroadcastReceiver Tutorial
Ahsanul Karim
 
PPTX
Making flow Mule
Giuseppe Fiore
 
DOC
User's Guide
butest
 
PDF
Ax2012 technical Upgrade process
Tariq Rafique
 
PPTX
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
Codecamp Romania
 
PPTX
AdvancedJava.pptx
DrPrabakaranPerumal
 
Implementation of Push Notification in React Native Android app using Firebas...
naseeb20
 
Writing native Mac apps in C# with Xamarin.Mac - Aaron Bockover
Xamarin
 
GNURAdioDoc-8
tutorialsruby
 
GNURAdioDoc-8
tutorialsruby
 
Roboconf Detailed Presentation
Vincent Zurczak
 
Maf Event Bus
Paolo Quadrani
 
Backtrack Manual Part6
Nutan Kumar Panda
 
Emulink: Simulink environment for PVS
edge7
 
Android development training programme , Day 3
DHIRAJ PRAVIN
 
WPF Windows Presentation Foundation A detailed overview Version1.2
Shahzad
 
How to Setup Real-Time Communication in odoo_ Using the Bus Service
Celine George
 
Dynamic autoselection and autotuning of machine learning models forcloud netw...
Venkat Projects
 
IBM MobileFirst Platform v7.0 POT App Mgmt Lab v1.1
Banking at Ho Chi Minh city
 
Managing multi-version applications in cics
Matthew Webster
 
Android Application Component: BroadcastReceiver Tutorial
Ahsanul Karim
 
Making flow Mule
Giuseppe Fiore
 
User's Guide
butest
 
Ax2012 technical Upgrade process
Tariq Rafique
 
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
Codecamp Romania
 
AdvancedJava.pptx
DrPrabakaranPerumal
 

More from Sameer Rathoud (8)

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

Recently uploaded (20)

PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Software Development Methodologies in 2025
KodekX
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 

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.