{"id":6481,"date":"2022-11-20T16:54:44","date_gmt":"2022-11-20T16:54:44","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/the-observer-pattern\/"},"modified":"2022-11-20T16:54:44","modified_gmt":"2022-11-20T16:54:44","slug":"the-observer-pattern","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/the-observer-pattern\/","title":{"rendered":"The Observer Pattern"},"content":{"rendered":"<p>The Observer Pattern is a behavioral pattern from the book &nbsp; &#8220;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">Design Patterns: Elements of Reusable Object-Oriented Software&#8221;<\/a>. It defines 1-to-n dependencies between objects so that changes to one object cause all dependent objects to be notified.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6479\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern.png\" alt=\"BehavioralPattern\" width=\"650\" height=\"329\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern.png 1234w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern-300x152.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern-1024x518.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/BehavioralPattern-768x388.png 768w\" sizes=\"auto, (max-width: 650px) 100vw, 650px\" \/><\/p>\n<p>The Observer Pattern solves a classical design issue: How can you ensure that all prospects are automatically notified if an important event has taken place?<\/p>\n<h2><span class=\"ez-toc-section\" id=\"The_Observer_Pattern\"><\/span>The Observer Pattern<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Purpose\"><\/span>Purpose<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>Defines 1-to-n dependencies between objects so that changes to one object cause all dependent objects to be notified.<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Also_known_as\"><\/span>Also known as<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>Publisher-Subscriber (short Pub\/Sub)<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Use_Case\"><\/span>Use Case<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>One abstraction depends on the state of another abstraction<\/li>\n<li>A change to one object implies a change to another object<\/li>\n<li>Objects should be notified of state changes of another object without being tightly coupled<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Structure\"><\/span>Structure<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5302\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/08\/Observer.png\" alt=\"Observer\" width=\"579\" height=\"220\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/08\/Observer.png 579w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/08\/Observer-300x114.png 300w\" sizes=\"auto, (max-width: 579px) 100vw, 579px\" \/><\/p>\n<p>&nbsp;<strong><code>Subject<\/code><\/strong><\/p>\n<ul>\n<li>Manages its collection of observers<\/li>\n<li>Allows the observers to register and unregister themself<strong><code><br \/><\/code><\/strong><\/li>\n<\/ul>\n<p><strong><code>Observer<\/code><\/strong><\/p>\n<ul>\n<li><strong><code><\/code><\/strong>Defines an interface to notify the observers<br \/><strong><code><\/code><\/strong><\/li>\n<\/ul>\n<p><strong><code>ConcreteObserver<\/code><\/strong><\/p>\n<ul>\n<li>Implements the interface<\/li>\n<li>Is notified by the<code> Subject<\/code><\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Example\"><\/span>Example<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The following program <code>observer.cpp<\/code> directly implements the previous <a href=\"https:\/\/en.wikipedia.org\/wiki\/Class_diagram\">class diagram<\/a>.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ observer.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;list&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;string&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Observer<\/span> {\r\n <span style=\"color: #9999ff;\">public:<\/span>\r\n  <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #555555;\">~<\/span>Observer(){};\r\n  <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> notify() <span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>;\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Subject<\/span> {\r\n <span style=\"color: #9999ff;\">public:<\/span>\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> registerObserver(Observer<span style=\"color: #555555;\">*<\/span> observer) {\r\n    observers.push_back(observer);\r\n  }\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> unregisterObserver(Observer<span style=\"color: #555555;\">*<\/span> observer) {\r\n    observers.remove(observer);\r\n  }\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> notifyObservers() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {                             <span style=\"color: #0099ff;\"><em>\/\/ (2)<\/em><\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #006699; font-weight: bold;\">auto<\/span> observer<span style=\"color: #555555;\">:<\/span> observers) observer<span style=\"color: #555555;\">-&gt;<\/span>notify();\r\n  }\r\n\r\n <span style=\"color: #9999ff;\">private:<\/span>\r\n  std<span style=\"color: #555555;\">::<\/span>list<span style=\"color: #555555;\">&lt;<\/span>Observer <span style=\"color: #555555;\">*&gt;<\/span> observers;\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">ConcreteObserverA<\/span> <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Observer {\r\n <span style=\"color: #9999ff;\">public:<\/span>\r\n    ConcreteObserverA(Subject<span style=\"color: #555555;\">&amp;<\/span> subject) <span style=\"color: #555555;\">:<\/span> subject_(subject) {\r\n        subject_.registerObserver(<span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    }\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> notify() <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"ConcreteObserverA::notify<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n    }\r\n <span style=\"color: #9999ff;\">private:<\/span> \r\n    Subject<span style=\"color: #555555;\">&amp;<\/span> subject_;                                   <em><span style=\"color: #0099ff;\"> \/\/ (3)<\/span><\/em>\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">ConcreteObserverB<\/span> <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Observer {\r\n <span style=\"color: #9999ff;\">public:<\/span>\r\n    ConcreteObserverB(Subject<span style=\"color: #555555;\">&amp;<\/span> subject) <span style=\"color: #555555;\">:<\/span> subject_(subject) {\r\n        subject_.registerObserver(<span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    }\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> notify() <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"ConcreteObserverB::notify<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n    }\r\n <span style=\"color: #9999ff;\">private:<\/span> \r\n    Subject<span style=\"color: #555555;\">&amp;<\/span> subject_;                                   <em><span style=\"color: #0099ff;\">\/\/ (4)<\/span><\/em>\r\n};\r\n\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>() {\r\n\r\n    std::cout &lt;&lt; '\\n';<br \/><br \/>    Subject subject;   \r\n    ConcreteObserverA observerA(subject);\r\n    ConcreteObserverB observerB(subject);\r\n\r\n    subject.notifyObservers();\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span>  <span style=\"color: #cc3300;\">\"    subject.unregisterObserver(observerA)<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n    subject.unregisterObserver(<span style=\"color: #555555;\">&amp;<\/span>observerA);         <em><span style=\"color: #0099ff;\">\/\/ (1)<\/span><\/em>\r\n    subject.notifyObservers();<br \/><br \/>    std::cout &lt;&lt; '\\n';\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The <code>Observer<\/code> supports the member function <code>notify<\/code>, and the <code>Subject<\/code> supports the member functions <code>registerObserver<\/code>, <code>unregisterObserver<\/code>, and <code>notifyObservers<\/code>. The concrete observers receive the subject in their constructor and use them to register themself for the notification. They have a reference to the subject (lines 3 and 4).&nbsp; Only <code>observerA<\/code> is unregistered in line (1). The member function <code>notifyObservers<\/code> goes through all registered observers and notifies them (line 2).<\/p>\n<p>The following screenshot shows the output of the program:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6480\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/observer_.png\" alt=\"observer \" width=\"400\" height=\"203\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/observer_.png 535w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/11\/observer_-300x153.png 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p>By the way, you may have noticed that I used no memory allocation in the previous program <code><span>observer.cpp<\/span><\/code>. This is how virtuality is typically used if you aren&#8217;t allowed to allocate memory, such as in deeply embedded systems. Here is the corresponding main function using memory allocation:<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>() {<br \/><br \/>    std::cout &lt;&lt; '\\n';\r\n\r\n    Subject<span style=\"color: #555555;\">*<\/span> subject <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> Subject;\r\n    Observer<span style=\"color: #555555;\">*<\/span> observerA <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> ConcreteObserverA(<span style=\"color: #555555;\">*<\/span>subject);\r\n    Observer<span style=\"color: #555555;\">*<\/span> observerB <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> ConcreteObserverB(<span style=\"color: #555555;\">*<\/span>subject);\r\n\r\n    subject<span style=\"color: #555555;\">-&gt;<\/span>notifyObservers();\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span>  <span style=\"color: #cc3300;\">\"    subject-&gt;unregisterObserver(observerA)\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n    subject<span style=\"color: #555555;\">-&gt;<\/span>unregisterObserver(observerA);\r\n    subject<span style=\"color: #555555;\">-&gt;<\/span>notifyObservers();\r\n\r\n    <span style=\"color: #006699; font-weight: bold;\">delete<\/span> observerA;\r\n    <span style=\"color: #006699; font-weight: bold;\">delete<\/span> observerB;\r\n\r\n    <span style=\"color: #006699; font-weight: bold;\">delete<\/span> subject;<br \/><br \/>    std::cout &lt;&lt; '\\n';\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Know_Uses\"><\/span>Know Uses<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The Observer Patten is often used in architectural patterns such as <a href=\"https:\/\/en.wikipedia.org\/wiki\/Model%E2%80%93view%E2%80%93controller\">Model-View-Controller<\/a> (MVC)&nbsp; for graphical user interfaces or <a href=\"https:\/\/en.wikipedia.org\/wiki\/Reactor_pattern\">Reactor<\/a> for event handling.<\/p>\n<ul>\n<li><strong>Model-View-Controller<\/strong>: The model represents the data and its logic. The model notifies its dependent component, such as the views. The views are responsible for representing the data, and the controller is for the user input.<\/li>\n<li><strong>Reactor<\/strong>: The Reactor registers the event handlers. The synchronous event demultiplexer (<code>select<\/code>) notifies the handles if an event occurs.<\/li>\n<\/ul>\n<p>I will dedicate an entire future post to both architectural patterns.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Variations\"><\/span>Variations<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The <code>Subject<\/code> in the program <code>observer.cpp<\/code> simply sends a notification. However, more advanced workflows are often implemented:<\/p>\n<p>The <code>Subject<\/code> sends a<\/p>\n<ul>\n<li>value.<\/li>\n<li>notification that a value is available. Afterward, the Observer has to pick it up.<\/li>\n<li>notification, including an indication of which value is available. The Observer picks it up if necessary.<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Related_Patterns\"><\/span>Related Patterns<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li>The<a href=\"https:\/\/en.wikipedia.org\/wiki\/Mediator_pattern\"> Mediator Pattern <\/a>establishes communication between the sender and the receiver. Each communication between the two endpoints goes, therefore, through the mediator. The Mediator and the Observer are pretty similar. The goal of the mediator is to decouple the sender and the receiver. On the contrary, the Observer established a one-way communication between the publisher and the subscriber.<\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"Pros_and_Cons\"><\/span>Pros and Cons<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<h4>Pros<\/h4>\n<ul>\n<li>New observers (subscribes) can easily be added to the publisher<\/li>\n<li>Observers can register and unregister themself at run time<\/li>\n<\/ul>\n<h4>Cons<\/h4>\n<ul>\n<li>Neither does the publisher provides a guarantee in which order the subscribers are notified, nor does it gives the assertion of how long the notification takes when you have many subscribers.<\/li>\n<li>The publisher may send a notification, but a subscriber is not alive anymore. To avoid this drawback, you can implement the destructor of the concrete observers in such a way that the concrete observers unregister themself in its destructor:<\/li>\n<\/ul>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">ConcreteObserverA<\/span> <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Observer {\r\n <span style=\"color: #9999ff;\">public:<\/span>\r\n    ConcreteObserverA(Subject<span style=\"color: #555555;\">&amp;<\/span> subject) <span style=\"color: #555555;\">:<\/span> subject_(subject) {\r\n        subject_.registerObserver(<span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    }\r\n    <span style=\"color: #555555;\">~<\/span>ConcreteObserverA() noexcept {\r\n        subject_.unregisterObserver(<span style=\"color: #006699; font-weight: bold;\">this<\/span>);\r\n    }\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> notify() <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {\r\n        std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"ConcreteObserverA::notify<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n    }\r\n <span style=\"color: #9999ff;\">private:<\/span> \r\n    Subject<span style=\"color: #555555;\">&amp;<\/span> subject_;\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The concrete observer <code>ConcreteObserverA<\/code> models the RAII Idiom: It registers itself in its constructor and unregisters itself in its destructor.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Whats_next\"><\/span>What&#8217;s next?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The <a href=\"https:\/\/en.wikipedia.org\/wiki\/Visitor_pattern\">Visitor Pattern<\/a> has an ambivalent reputation. On one hand, enables the Visitor <a href=\"https:\/\/en.wikipedia.org\/wiki\/Double_dispatch\">Double Dispatch<\/a>. On the other hand, the Visitor is pretty complicated to implement. Let me introduce the Visitor Pattern in my next post.<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Observer Pattern is a behavioral pattern from the book &nbsp; &#8220;Design Patterns: Elements of Reusable Object-Oriented Software&#8221;. It defines 1-to-n dependencies between objects so that changes to one object cause all dependent objects to be notified.<\/p>\n","protected":false},"author":21,"featured_media":6479,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[379],"tags":[],"class_list":["post-6481","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-patterns"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6481","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=6481"}],"version-history":[{"count":0,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6481\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/6479"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=6481"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=6481"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=6481"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}