SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Semelhante a Observer dp

Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Augmelbournepatterns
 
Observer pattern
Observer patternObserver pattern
Observer patternanshu_atri
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
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 JVMNetesh Kumar
 
Strange Async Code - ReaxtiveX
Strange Async Code - ReaxtiveXStrange Async Code - ReaxtiveX
Strange Async Code - ReaxtiveXMatthew Will
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaNexThoughts Technologies
 
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 Patternsassinha
 
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 AndroidSperasoft
 
Combine Framework
Combine FrameworkCombine Framework
Combine FrameworkCleveroad
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator PatternJonathan Simon
 
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 ARMOpen Mobile Alliance
 

Semelhante a 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
 

Mais de 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 of mobile apps
Testing of mobile appsTesting of mobile apps
Testing of mobile appsISsoft
 
Testing, qa, qc. what the difference
Testing, qa, qc. what the differenceTesting, qa, qc. what the difference
Testing, qa, qc. what the differenceISsoft
 
Ranorex presentation
Ranorex presentationRanorex presentation
Ranorex presentationISsoft
 
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 ...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 beginnersISsoft
 
Отдел юзабилити
Отдел юзабилитиОтдел юзабилити
Отдел юзабилитиISsoft
 
ToDoList
ToDoListToDoList
ToDoListISsoft
 
Prototype presentation
Prototype presentationPrototype presentation
Prototype presentationISsoft
 
решение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте baрешение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте baISsoft
 
решение одной из ключевых проблем компетенции 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 sitesISsoft
 
Bdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проектеBdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проектеISsoft
 
инфотекс автоматизация тестирования
инфотекс   автоматизация тестированияинфотекс   автоматизация тестирования
инфотекс автоматизация тестированияISsoft
 

Mais de 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 как способ построения коммуникации на проекте
 
инфотекс автоматизация тестирования
инфотекс   автоматизация тестированияинфотекс   автоматизация тестирования
инфотекс автоматизация тестирования
 

Último

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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 2024The Digital Insurer
 
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.pdfsudhanshuwaghmare1
 
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 WorkerThousandEyes
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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 2024Rafal Los
 
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 organizationRadu Cotescu
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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...Miguel Araújo
 
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?Igalia
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Último (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
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
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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 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?
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

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