Download presentation
Presentation is loading. Please wait.
1
Observer Design Pattern
observing changes
2
Observer Motivation objects (observers) need to synchronize behavior with some other object (subject): observe changing subject’s state ex: bar chart and bar graph need to know when original spreadsheet values change
3
Observer Implementation
observers subscribe to change state notifications, while subjects publish changes by notifying observers or sending them messages (synonymous terms) another name for pattern – publish-subscribe common way to implement GUI interfaces (foundation of so-called model-view-controller architectural pattern) the “business logic” is in subject hierarchy the “presentation logic” is in observer hierarchy if using abstract/concrete classes abstract observer/subject – implement registration/notification functionality concrete observer/subject – implement subject state and state acquisition by observer there may be a registry of subjects for observers to subscribe to behavioral pattern
4
Communication Methods: Push & Pull
observer needs to communicate state change information to subject two communication methods push – state change is in message itself may require large message not all concrete subjects need all the data subject may push a reference to itself pull – observer queries the state of subject after receiving notification observer needs to keep reference to subject subject needs to implement getters
5
Observer UML Diagram (Push Method)
+notify()
6
Observer UML Diagram (Pull Method)
7
(Forward) Class Declaration
in C++, any named construct must be declared before use a class may be declared by class definition (forward) class declaration syntax class NameOfClass; after forward declaration, can declare pointers/references (but not objects) of this class used when classes mutually refer to each other, or for better program structure Class A; // declaration Class B{ B(A*p):p_(p){} private: A *p_; }; // definition Class A{ ... };
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.