SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
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 . . .

Weitere ähnliche Inhalte

Was ist angesagt?

Parameter Estimation User Guide
Parameter Estimation User GuideParameter Estimation User Guide
Parameter Estimation User Guide
Andy Salmon
 
New Microsoft Word Document.doc
New Microsoft Word Document.docNew Microsoft Word Document.doc
New Microsoft Word Document.doc
butest
 

Was ist angesagt? (12)

Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer Pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android Montréal
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com
 
Parameter Estimation User Guide
Parameter Estimation User GuideParameter Estimation User Guide
Parameter Estimation User Guide
 
MySQL Manchester TT - JSON Example
MySQL Manchester TT - JSON ExampleMySQL Manchester TT - JSON Example
MySQL Manchester TT - JSON Example
 
Triggers and active database
Triggers and active databaseTriggers and active database
Triggers and active database
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 
Realizing an Application Use Case
Realizing an Application Use CaseRealizing an Application Use Case
Realizing an Application Use Case
 
New Microsoft Word Document.doc
New Microsoft Word Document.docNew Microsoft Word Document.doc
New Microsoft Word Document.doc
 

Andere mochten auch

Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patterns
beloslab
 
Observer pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expressionObserver pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expression
LearningTech
 
Design patterns
Design patternsDesign patterns
Design patterns
ISsoft
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
babak danyal
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer pattern
pixelblend
 

Andere mochten auch (16)

Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patterns
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 
Observation Method
Observation MethodObservation Method
Observation Method
 
Observer Software Design Pattern
Observer Software Design Pattern Observer Software Design Pattern
Observer Software Design Pattern
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Observer pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expressionObserver pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expression
 
Design patterns
Design patternsDesign patterns
Design patterns
 
The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer pattern
 

Ähnlich wie Observer design pattern

Writing native Mac apps in C# with Xamarin.Mac - Aaron Bockover
Writing native Mac apps in C# with Xamarin.Mac - Aaron BockoverWriting native Mac apps in C# with Xamarin.Mac - Aaron Bockover
Writing native Mac apps in C# with Xamarin.Mac - Aaron Bockover
Xamarin
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
DHIRAJ PRAVIN
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver Tutorial
Ahsanul Karim
 
User's Guide
User's GuideUser's Guide
User's Guide
butest
 
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
Iasi code camp 12 october 2013   adrian marinica - windows 8 and windows phon...Iasi code camp 12 october 2013   adrian marinica - windows 8 and windows phon...
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
Codecamp Romania
 
Windows phone 7 series
Windows phone 7 seriesWindows phone 7 series
Windows phone 7 series
openbala
 

Ähnlich wie Observer design pattern (20)

Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...
 
Writing native Mac apps in C# with Xamarin.Mac - Aaron Bockover
Writing native Mac apps in C# with Xamarin.Mac - Aaron BockoverWriting native Mac apps in C# with Xamarin.Mac - Aaron Bockover
Writing native Mac apps in C# with Xamarin.Mac - Aaron Bockover
 
GNURAdioDoc-8
GNURAdioDoc-8GNURAdioDoc-8
GNURAdioDoc-8
 
GNURAdioDoc-8
GNURAdioDoc-8GNURAdioDoc-8
GNURAdioDoc-8
 
Roboconf Detailed Presentation
Roboconf Detailed PresentationRoboconf Detailed Presentation
Roboconf Detailed Presentation
 
Maf Event Bus
Maf Event BusMaf Event Bus
Maf Event Bus
 
Backtrack Manual Part6
Backtrack Manual Part6Backtrack Manual Part6
Backtrack Manual Part6
 
Emulink: Simulink environment for PVS
Emulink: Simulink environment for PVSEmulink: Simulink environment for PVS
Emulink: Simulink environment for PVS
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
WPF Windows Presentation Foundation A detailed overview Version1.2
WPF Windows Presentation Foundation A detailed overview Version1.2WPF Windows Presentation Foundation A detailed overview Version1.2
WPF Windows Presentation Foundation A detailed overview Version1.2
 
Dynamic autoselection and autotuning of machine learning models forcloud netw...
Dynamic autoselection and autotuning of machine learning models forcloud netw...Dynamic autoselection and autotuning of machine learning models forcloud netw...
Dynamic autoselection and autotuning of machine learning models forcloud netw...
 
IBM MobileFirst Platform v7.0 POT App Mgmt Lab v1.1
IBM MobileFirst Platform  v7.0 POT App Mgmt Lab v1.1IBM MobileFirst Platform  v7.0 POT App Mgmt Lab v1.1
IBM MobileFirst Platform v7.0 POT App Mgmt Lab v1.1
 
Managing multi-version applications in cics
Managing multi-version applications in cicsManaging multi-version applications in cics
Managing multi-version applications in cics
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver Tutorial
 
Making flow Mule
Making flow MuleMaking flow Mule
Making flow Mule
 
User's Guide
User's GuideUser's Guide
User's Guide
 
Ax2012 technical Upgrade process
Ax2012 technical Upgrade processAx2012 technical Upgrade process
Ax2012 technical Upgrade process
 
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
Iasi code camp 12 october 2013   adrian marinica - windows 8 and windows phon...Iasi code camp 12 october 2013   adrian marinica - windows 8 and windows phon...
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
 
AdvancedJava.pptx
AdvancedJava.pptxAdvancedJava.pptx
AdvancedJava.pptx
 
Windows phone 7 series
Windows phone 7 seriesWindows phone 7 series
Windows phone 7 series
 

Mehr von Sameer Rathoud

Mehr von Sameer Rathoud (8)

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

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

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.