SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Design Patterns
Observer
Written by: Andrey Stakhievich,
Automation Department,
Coherent Solutions
Definition
Observer defines:
a one-to-many dependency between objects
so that when one object changes state,
all its dependents are notified and updated
automatically.
Description
• The observer design pattern enables a subscriber to
register with and receive notifications from a provider. It
is suitable for any scenario that requires push-based
notification.
• The pattern defines a provider (also known as a subject
or an observable) and zero, one, or more observers.
• Observers register with the provider, and whenever a
predefined condition, event, or state change occurs, the
provider automatically notifies all observers by calling
one of their methods.
• In this method call, the provider can also provide current
state information to observers.
Real Life Metaphor
Some 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.
Check List
1.
2.
3.
4.
5.
6.
7.
8.

Differentiate between the core (or independent) functionality and
the optional (or dependent) functionality.
Model the independent functionality with a "subject" abstraction.
Model the dependent functionality with an "observer" hierarchy.
The Subject is coupled only to the Observer base class.
The client configures the number and type of Observers.
Observers register themselves with the Subject.
The Subject broadcasts events to all registered Observers.
The Subject may "push" information at the Observers, or, the
Observers may "pull" the information they need from the Subject.
UML Diagram
Entities
• Subject (IObservable)
– knows its observers. Any number of Observer objects may observe a subject
– provides an interface for attaching and detaching Observer objects.

• Concrete Subject
– stores state of interest to Concrete Observer
– sends a notification to its observers when its state changes

• Observer (IObserver)
– defines an updating interface for objects that should be notified of changes in
a subject.

• Concrete Observer
– maintains a reference to a Concrete Subject object
– stores state that should stay consistent with the subject's
– implements the Observer updating interface to keep its state consistent with
the subject's
.Net Implementation
In the .NET Framework, the observer design
pattern is applied by implementing the generic
System.IObservable<T> and
System.IObserver<T> interfaces.
The generic type parameter represents the type
that provides notification information.
IObserver
public interface IObserver<in T>
{
//Notifies the observer that the provider has finished sending push-based
//notifications.
void OnCompleted();
//Notifies the observer that the provider has experienced an error
//condition. An object that provides additional information about the error.
void OnError(Exception error);
//Provides the observer with new data. The current notification information.
void OnNext(T value);
}
IObservable
public interface IObservable<out T>
{
//Summary:
//Notifies the provider that an observer is to receive notifications.
//
//Parameters:
//observer:
//The object that is to receive notifications.
//
//Returns:
//A reference to an interface that allows observers to stop receiving notifications
//before the provider has finished sending them.
IDisposable Subscribe (IObserver <T>observer);
}
Final Comparison
Chain of Responsibility, Command, Mediator, and
Observer, address how you can decouple senders and
receivers, but with different trade-offs.
Chain of Responsibility passes a sender request along a
chain of potential receivers.
Command normally specifies a sender-receiver
connection with a subclass.
Mediator has senders and receivers reference each other
indirectly.
Observer defines a very decoupled interface that allows
for multiple receivers to be configured at run-time.
THE END…
Have a look at a real world example on TFS:
http://minsk-app-tfs1:8080/ $/CSI - Training
Center/Clients/Automation/OOP/DP/Observer/
But..
This presentation could not be
completed without…
The sources of information:
1. http://www.dofactory.com/Patterns/PatternObserver.aspx
2. http://www.vincehuston.org/dp/observer.html
3. Design Patterns: Elements of Reusable Object-oriented
Software, by Erich Gamma, Richard Helm, Ralph Johnson, John
Vlissides, 1995 – “Gang of Four”
4. Special Thanks to Denis Sajin for providing the cute cats

Weitere ähnliche Inhalte

Ähnlich wie Observer dp

Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Aug
melbournepatterns
 

Ähnlich wie Observer dp (20)

pattern v
pattern vpattern v
pattern v
 
Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Aug
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Rxandroid
RxandroidRxandroid
Rxandroid
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
 
A4WSN
A4WSNA4WSN
A4WSN
 
Strange Async Code - ReaxtiveX
Strange Async Code - ReaxtiveXStrange Async Code - ReaxtiveX
Strange Async Code - ReaxtiveX
 
Listeners and filters in servlet
Listeners and filters in servletListeners and filters in servlet
Listeners and filters in servlet
 
Introduction to reactive programming
Introduction to reactive programmingIntroduction to reactive programming
Introduction to reactive programming
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
IoT in salsa Serverless
IoT in salsa ServerlessIoT in salsa Serverless
IoT in salsa Serverless
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patterns
 
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on AndroidSperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on Android
 
Combine Framework
Combine FrameworkCombine Framework
Combine Framework
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
 
Reactors.io
Reactors.ioReactors.io
Reactors.io
 
LWM2M Introduction - Edinburgh 2016 Workshop with ARM
LWM2M Introduction - Edinburgh 2016 Workshop with ARMLWM2M Introduction - Edinburgh 2016 Workshop with ARM
LWM2M Introduction - Edinburgh 2016 Workshop with ARM
 

Mehr von ISsoft

Sql инъекции в тестировании
Sql инъекции в тестированииSql инъекции в тестировании
Sql инъекции в тестировании
ISsoft
 
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
ISsoft
 
Testing, qa, qc. what the difference
Testing, qa, qc. what the differenceTesting, qa, qc. what the difference
Testing, qa, qc. what the difference
ISsoft
 
Ranorex presentation
Ranorex presentationRanorex presentation
Ranorex presentation
ISsoft
 
Bdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проектеBdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проекте
ISsoft
 
Тестирование требований
Тестирование требованийТестирование требований
Тестирование требований
ISsoft
 
Тестирование требований
Тестирование требованийТестирование требований
Тестирование требований
ISsoft
 
Sql practise for beginners
Sql practise for beginnersSql practise for beginners
Sql practise for beginners
ISsoft
 
Отдел юзабилити
Отдел юзабилитиОтдел юзабилити
Отдел юзабилити
ISsoft
 
ToDoList
ToDoListToDoList
ToDoList
ISsoft
 
Prototype presentation
Prototype presentationPrototype presentation
Prototype presentation
ISsoft
 
решение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте baрешение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте ba
ISsoft
 
решение одной из ключевых проблем компетенции Ba специалистов
решение одной из ключевых проблем компетенции Ba специалистоврешение одной из ключевых проблем компетенции Ba специалистов
решение одной из ключевых проблем компетенции Ba специалистов
ISsoft
 
Development of automated tests for ext js based web sites
Development of automated tests for ext js based web sitesDevelopment of automated tests for ext js based web sites
Development of automated tests for ext js based web sites
ISsoft
 
Bdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проектеBdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проекте
ISsoft
 
инфотекс автоматизация тестирования
инфотекс   автоматизация тестированияинфотекс   автоматизация тестирования
инфотекс автоматизация тестирования
ISsoft
 

Mehr von ISsoft (20)

Sql инъекции в тестировании
Sql инъекции в тестированииSql инъекции в тестировании
Sql инъекции в тестировании
 
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
 
Testing of mobile apps
Testing of mobile appsTesting of mobile apps
Testing of mobile apps
 
Testing, qa, qc. what the difference
Testing, qa, qc. what the differenceTesting, qa, qc. what the difference
Testing, qa, qc. what the difference
 
Ranorex presentation
Ranorex presentationRanorex presentation
Ranorex presentation
 
Bugs
BugsBugs
Bugs
 
Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...
Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...
Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...
 
Bdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проектеBdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проекте
 
Тестирование требований
Тестирование требованийТестирование требований
Тестирование требований
 
Тестирование требований
Тестирование требованийТестирование требований
Тестирование требований
 
Sql practise for beginners
Sql practise for beginnersSql practise for beginners
Sql practise for beginners
 
Отдел юзабилити
Отдел юзабилитиОтдел юзабилити
Отдел юзабилити
 
ToDoList
ToDoListToDoList
ToDoList
 
ISTQB
ISTQBISTQB
ISTQB
 
Prototype presentation
Prototype presentationPrototype presentation
Prototype presentation
 
решение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте baрешение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте ba
 
решение одной из ключевых проблем компетенции Ba специалистов
решение одной из ключевых проблем компетенции Ba специалистоврешение одной из ключевых проблем компетенции Ba специалистов
решение одной из ключевых проблем компетенции Ba специалистов
 
Development of automated tests for ext js based web sites
Development of automated tests for ext js based web sitesDevelopment of automated tests for ext js based web sites
Development of automated tests for ext js based web sites
 
Bdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проектеBdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проекте
 
инфотекс автоматизация тестирования
инфотекс   автоматизация тестированияинфотекс   автоматизация тестирования
инфотекс автоматизация тестирования
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Observer dp

  • 1. Design Patterns Observer Written by: Andrey Stakhievich, Automation Department, Coherent Solutions
  • 2. Definition Observer defines: a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • 3. Description • The observer design pattern enables a subscriber to register with and receive notifications from a provider. It is suitable for any scenario that requires push-based notification. • The pattern defines a provider (also known as a subject or an observable) and zero, one, or more observers. • Observers register with the provider, and whenever a predefined condition, event, or state change occurs, the provider automatically notifies all observers by calling one of their methods. • In this method call, the provider can also provide current state information to observers.
  • 4. Real Life Metaphor Some 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.
  • 5. Check List 1. 2. 3. 4. 5. 6. 7. 8. Differentiate between the core (or independent) functionality and the optional (or dependent) functionality. Model the independent functionality with a "subject" abstraction. Model the dependent functionality with an "observer" hierarchy. The Subject is coupled only to the Observer base class. The client configures the number and type of Observers. Observers register themselves with the Subject. The Subject broadcasts events to all registered Observers. The Subject may "push" information at the Observers, or, the Observers may "pull" the information they need from the Subject.
  • 7. Entities • Subject (IObservable) – knows its observers. Any number of Observer objects may observe a subject – provides an interface for attaching and detaching Observer objects. • Concrete Subject – stores state of interest to Concrete Observer – sends a notification to its observers when its state changes • Observer (IObserver) – defines an updating interface for objects that should be notified of changes in a subject. • Concrete Observer – maintains a reference to a Concrete Subject object – stores state that should stay consistent with the subject's – implements the Observer updating interface to keep its state consistent with the subject's
  • 8. .Net Implementation In the .NET Framework, the observer design pattern is applied by implementing the generic System.IObservable<T> and System.IObserver<T> interfaces. The generic type parameter represents the type that provides notification information.
  • 9. IObserver public interface IObserver<in T> { //Notifies the observer that the provider has finished sending push-based //notifications. void OnCompleted(); //Notifies the observer that the provider has experienced an error //condition. An object that provides additional information about the error. void OnError(Exception error); //Provides the observer with new data. The current notification information. void OnNext(T value); }
  • 10. IObservable public interface IObservable<out T> { //Summary: //Notifies the provider that an observer is to receive notifications. // //Parameters: //observer: //The object that is to receive notifications. // //Returns: //A reference to an interface that allows observers to stop receiving notifications //before the provider has finished sending them. IDisposable Subscribe (IObserver <T>observer); }
  • 11. Final Comparison Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers. Command normally specifies a sender-receiver connection with a subclass. Mediator has senders and receivers reference each other indirectly. Observer defines a very decoupled interface that allows for multiple receivers to be configured at run-time.
  • 12. THE END… Have a look at a real world example on TFS: http://minsk-app-tfs1:8080/ $/CSI - Training Center/Clients/Automation/OOP/DP/Observer/
  • 13. But.. This presentation could not be completed without… The sources of information: 1. http://www.dofactory.com/Patterns/PatternObserver.aspx 2. http://www.vincehuston.org/dp/observer.html 3. Design Patterns: Elements of Reusable Object-oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, 1995 – “Gang of Four” 4. Special Thanks to Denis Sajin for providing the cute cats