We strongly recommend to refer below Set 1 before moving on to this post.
In Set 1, we discussed below problem, a solution for the problem without Observer pattern and problems with the solution.
Suppose we are building a cricket app that notifies viewers about the information such as current score, run rate etc. Suppose we have made two display elements CurrentScoreDisplay and AverageScoreDisplay. CricketData has all the data (runs, bowls etc.) and whenever data changes the display elements are notified with new data and they display the latest data accordingly
Applying Observer pattern to above problem:
Let us see how we can improve the design of our application using observer pattern. If we observe the flow of data we can easily see that the CricketData and display elements follow subject-observers relationship.
Average Score Display: Run Rate: 8.823529 PredictedScore: 441 Current Score Display: Runs: 90 Wickets:2 Overs: 10.2 Current Score Display: Runs: 90 Wickets:2 Overs: 10.2
Note: Now we can add/delete as many observers without changing the subject.
- Head First Design Patterns book (highly recommended)
This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Command Pattern
- Observer Pattern | Set 1 (Introduction)
- Singleton Design Pattern | Implementation
- Decorator Pattern | Set 1 (Background)
- The Decorator Pattern | Set 2 (Introduction and Design)
- Decorator Pattern | Set 3 (Coding the Design)
- Strategy Pattern | Set 1 (Introduction)
- Strategy Pattern | Set 2 (Implementation)
- Adapter Pattern
- Iterator Pattern
- Curiously recurring template pattern (CRTP)
- Flyweight Design Pattern
- Implementing Iterator pattern of a single Linked List
- Singleton Design Pattern | Introduction
- Java Singleton Design Pattern Practices with Examples