Observer Pattern | Set 2 (Implementation)
We strongly recommend to refer below Set 1 before moving on to this post.
Observer Pattern -Introduction
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
Please Login to comment...