{"id":2975,"date":"2020-07-22T13:12:41","date_gmt":"2020-07-22T13:12:41","guid":{"rendered":"https:\/\/eluminoustechnologies.com\/blog\/?p=2975"},"modified":"2025-10-08T10:50:02","modified_gmt":"2025-10-08T10:50:02","slug":"observer-design-pattern-case-study","status":"publish","type":"post","link":"https:\/\/eluminoustechnologies.com\/blog\/observer-design-pattern-case-study\/","title":{"rendered":"What is Observer Design Pattern A Brief Guide with a Case Study"},"content":{"rendered":"<p>Software design patterns are tried and tested solutions to problems that developers commonly face while creating software. If you\u2019d like an in-depth explanation of software design patterns and their benefits, do check out this post we did on the subject &#8211; What Are Software Design Patterns &amp; An Introduction to Factory Design Pattern.<br \/>\nThat said, software design patterns are not a one-size-fits-all solution. There are, in all, 23 basic types of software design pattern and each software development problem necessitates the use of one or more of them.<br \/>\nIt\u2019s one such pattern that we\u2019re going to talk about here. Read on to know what is observer design pattern, its pros and cons, and when to use it.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"#\" data-href=\"https:\/\/eluminoustechnologies.com\/blog\/observer-design-pattern-case-study\/#what-is-observer-design-pattern\" >What is Observer Design Pattern?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"#\" data-href=\"https:\/\/eluminoustechnologies.com\/blog\/observer-design-pattern-case-study\/#a-case-study-example-of-observer-design-pattern\" >A Case Study Example of Observer Design Pattern<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"#\" data-href=\"https:\/\/eluminoustechnologies.com\/blog\/observer-design-pattern-case-study\/#applicability-of-observer-design-pattern\" >Applicability of Observer Design Pattern<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"#\" data-href=\"https:\/\/eluminoustechnologies.com\/blog\/observer-design-pattern-case-study\/#observer-design-pattern-usage\" >Observer Design Pattern Usage<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"#\" data-href=\"https:\/\/eluminoustechnologies.com\/blog\/observer-design-pattern-case-study\/#what-are-the-pros-and-cons-of-observer-design-pattern\" >What are the Pros and Cons of Observer Design Pattern?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"#\" data-href=\"https:\/\/eluminoustechnologies.com\/blog\/observer-design-pattern-case-study\/#when-to-use-observer-design-pattern\" >When to Use Observer Design Pattern?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"#\" data-href=\"https:\/\/eluminoustechnologies.com\/blog\/observer-design-pattern-case-study\/#summing-it-up\" >Summing It Up<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"what-is-observer-design-pattern\"><\/span>What is Observer Design Pattern?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Observer pattern is classified under the behavioural type of software design patterns. Behavioural patterns deal with the communication between different objects of the classes.<br \/>\nThe observer design pattern, as such, enables one object (also called an observable or subject) to communicate a change in its state to other objects (also called an observer or object) that are observing it. In other words, the subject alerts the objects observing it every time it changes.<br \/>\nObserver pattern ensures a clear separation between the subject and the observer objects. It lets you define the boundaries between various modules, which improves the maintainability and reusability of your software.<br \/>\nIn this way, the observer pattern lets you notify other objects about the change in the subject\u2019s state while ensuring a high level of collaboration, ease of use, and loose coupling.<\/p>\n<p>Let\u2019s understand this with a simple real-world analogy. Say, you found a great website that sums up all the important news of the day via a newsletter. You liked the content and subscribe to this newsletter. You continue to enjoy the daily newsletters, until the day you don\u2019t because of any number of reasons. So, you decide to withdraw your subscription to the website. Bear in mind that there are probably thousands of people subscribing or unsubscribing at the same time as you.<br \/>\nIn software development, the news website and its users (i.e. you) constitute an observer design pattern. While the website is the subject here, the subscribers are the observers. So, every time the subject\u2019s state changes, it broadcasts the same to its observers, who then go onto update themselves and display those changes.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"a-case-study-example-of-observer-design-pattern\"><\/span>A Case Study Example of Observer Design Pattern<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Let\u2019s take a real-life use case to understand how observer design pattern makes it easier to create a system where you can get a set of objects interested in the changes that are happening to another object.<\/p>\n<h3>Problem:<\/h3>\n<p>Assume you have two types of objects \u2013 ShareHolder and ShareMarket. The former wants to sell one unit when the share price drops by $10. Normally, the ShareHolder will do this by constantly checking the share price movement on the index. It\u2019s obvious that such an approach will lead to a lot of time wastage and might even cause the ShareHolder to miss the moment when the share price does drop by $10.<\/p>\n<h3>Solution:<\/h3>\n<p>In this case, the observer design pattern is used to design a publisher and subscriber pattern, similar to the newsletter example we saw previously. Here, the ShareMarket is the object whose state the other object, ShareHolder, is interested in. As such, the former is the publisher and the latter, the subscriber.<br \/>\nThe publisher will notify all its subscribers whenever its state changes. The subscriber(s) can then choose what to do with that information, i.e. they can either continue with the subscription or unsubscribe once their stated purpose is achieved.<br \/>\nThis arrangement is perfectly illustrated by the below image,<\/p>\n<p><img decoding=\"async\" class=\"size-full wp-image-2987 aligncenter lazyload\" data-src=\"https:\/\/b4130876.smushcdn.com\/4130876\/wp-content\/uploads\/2020\/07\/use-case.png?lossy=2&strip=1&webp=1\" alt=\"use-case-observer-pattern\" width=\"536\" height=\"204\" title=\"\" data-srcset=\"https:\/\/b4130876.smushcdn.com\/4130876\/wp-content\/uploads\/2020\/07\/use-case.png?lossy=2&amp;strip=1&amp;webp=1 536w, https:\/\/b4130876.smushcdn.com\/4130876\/wp-content\/uploads\/2020\/07\/use-case.png?size=128x49&amp;lossy=2&amp;strip=1&amp;webp=1 128w, https:\/\/b4130876.smushcdn.com\/4130876\/wp-content\/uploads\/2020\/07\/use-case.png?size=256x97&amp;lossy=2&amp;strip=1&amp;webp=1 256w, https:\/\/b4130876.smushcdn.com\/4130876\/wp-content\/uploads\/2020\/07\/use-case.png?size=384x146&amp;lossy=2&amp;strip=1&amp;webp=1 384w\" data-sizes=\"auto\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" style=\"--smush-placeholder-width: 536px; --smush-placeholder-aspect-ratio: 536\/204;\" data-original-sizes=\"(max-width: 536px) 100vw, 536px\"><\/p>\n<p>Note &#8211; In the observer design pattern, all the subscribers have to implement the same interface and the publisher must communicate via that interface only.<\/p>\n<p>As mentioned previously, the ShareHolder is the subscriber who will be notified by the publisher (ShareMarket) when the share price drops by $10. Once the subscriber achieves their intended goal of selling a share, they can unsubscribe from the publisher to avoid receiving unwanted notifications.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"applicability-of-observer-design-pattern\"><\/span>Applicability of Observer Design Pattern<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Let\u2019s look at how you can implement a <a href=\"https:\/\/eluminoustechnologies.com\/hire-developers\/php\/\" target=\"_blank\" rel=\"noopener\">PHP-based system<\/a> where a change in the state of one object requires a change in the state of other objects. Note that PHP offers several inbuilt interfaces to implement an observer design pattern. The one featured below is a standard template.<br \/>\nSplSubject Interface<\/p>\n<pre class=\"lang:default decode:true\">SplSubject Interface\r\ninterface SplSubject {\r\n\r\n\/**\r\n* Attach an SplObserve\r\n* @param SplObserver $observer\r\n* @return void \r\n*\/\r\npublic function attach (SplObserver $observer);\r\n\r\n\/**\r\n* Detach an observer\r\n* @param SplObserver $observe\r\n* @return void\r\n*\/\r\npublic function detach (SplObserver $observer);\r\n\r\n\/**\r\n* Notify an observer\r\n* @return void \r\n*\/\r\npublic function notify ();\r\n\r\n}\r\n<\/pre>\n<p>SplObserver Interface<\/p>\n<pre class=\"lang:default decode:true\">interface SplObserver {\r\n\r\n\/**\r\n* Receive update from subject\r\n* @param SplSubject $subject\r\n* @return void \r\n*\/\r\npublic function update (SplSubject $subject);\r\n\r\n}\r\n<\/pre>\n<p>Here, the attach() function allows us to register or link an observer (subscriber) to a subject (publisher). Similarly, detach() is used to unregister or unlink a publisher and a disinterested observer.<br \/>\nThe notify() method communicates a change in state to all subscribed observers, following which the update() is called on each observer.<br \/>\nA Subject\/Publisher Implementation<\/p>\n<pre class=\"lang:default decode:true\">use SplSubject;\r\nuse SplObserver;\r\n\r\nclass Publisher implements SplSubject\r\n{\r\n\/**\r\n* @var array\r\n*\/\r\nprotected $linkedList = array();\r\n\r\n\/**\r\n* @var array\r\n*\/\r\nprotected $observers = array();\r\n\r\n\r\n\/**\r\n*\r\n* @param string\r\n*\/\r\n\r\nprotected $name;\r\n\r\n\/**\r\n*\r\n* @param string\r\n*\/\r\n\r\nprotected $event;\r\n\r\n\r\npublic function __construct($name)\r\n{\r\n\r\n$this-&gt;name = $name;\r\n}\r\n\r\n\/**\r\n* Associate an observer\r\n*\r\n* @param SplObserver $observer\r\n* @return Publisher;\r\n*\/\r\n\r\npublic function attach(SplObserver $observer)\r\n{\r\n$observerKey = spl_object_hash($observer);\r\n$this-&gt;observers[$observerKey] = $observer;\r\n$this-&gt;linkedList[$observerKey] = $observer-&gt;getPriority();\r\narsort($this-&gt;linkedList);\r\n}\r\n\r\n\/**\r\n* @param SplObserver $observer\r\n* @return void\r\n*\/\r\npublic function detach(SplObserver $observer)\r\n{\r\n$observerKey = spl_object_hash($observer);\r\nunset($this-&gt;observers[$observerKey]);\r\nunset($this-&gt;linkedList[$observerKey]);\r\n}\r\n\r\n\/**\r\n* @return void\r\n*\/\r\npublic function notify()\r\n{\r\nforeach ($this-&gt;linkedList as $key =&gt; $value) {\r\n$this-&gt;observers[$key]-&gt;update($this);\r\n}\r\n}\r\n\r\n\/**\r\n* Set or update event \r\n*\r\n* @param $event\r\n* @return void\r\n*\/\r\npublic function setEvent($event)\r\n{\r\n$this-&gt;event = $event;\r\n$this-&gt;notify();\r\n}\r\n\r\n\/**\r\n* @return string\r\n*\/\r\npublic function getEvent()\r\n{\r\nreturn $this-&gt;event;\r\n}\r\n\r\npublic function getSubscribers()\r\n{\r\nreturn $this-&gt;getSubscribers();\r\n}\r\n\r\n}\r\n<\/pre>\n<p>Here, we define an attach() method so that an observer instance is accepted as an argument. And as we saw previously, the method lets you associate the observer with the observable, i.e. subject. Similarly, the detach() method is used to detach the two.<br \/>\nThe notify() method loops through the linked list, acquires the subscriber\u2019s key, uses it to locate the said observer, and then calls update() on that observer.<br \/>\nNote \u2013 The linked list is arranged in a way so that the highest priority observer gets alerted first.<br \/>\nThe setEvent() function accepts the argument of an event you want to broadcast before calling notify(), which then calls update() in all observer objects.<br \/>\nAn Observer\/Subscriber Implementation<\/p>\n<pre class=\"lang:default decode:true\">use SplObserver;\r\nuse SplSubject;\r\n\r\nclass Observer implements SplObserver\r\n{\r\n\/**\r\n* @var string\r\n*\/\r\nprotected $name;\r\n\r\n\/**\r\n* @var int\r\n*\/\r\nprotected $priority = 0;\r\n\r\n\r\n\/**\r\n* Accepts observer name and priority, default to zero\r\n*\/\r\npublic function __construct($name, $priority=0)\r\n{\r\n$this-&gt;name =$name;\r\n$this-&gt;priority =$priority;\r\n}\r\n\r\n\/**\r\n* Receive update from subject and print result\r\n*\r\n* @param SplSubject $publisher\r\n* @return void\r\n*\/\r\npublic function update(SplSubject $publisher){\r\n\r\nprint_r($this-&gt;name.': '. $publisher-&gt;getEvent(). PHP_EOL);\r\n\r\n}\r\n\r\n\/**\r\n* Get observer priority\r\n* \r\n* @return int\r\n*\/\r\npublic function getPriority(){\r\nreturn $this-&gt;priority;\r\n}\r\n\r\n}\r\n<\/pre>\n<h2><span class=\"ez-toc-section\" id=\"observer-design-pattern-usage\"><\/span>Observer Design Pattern Usage<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Here\u2019s an observer pattern use case where you broadcast an event to your team via Zoom. Now, some of your team members are on vacation and only reachable through email. Additionally, you also want a live feed of this broadcast on the main screen in your office. This is how you can implement all of that with observer design pattern:<\/p>\n<pre class=\"lang:default decode:true\">$noty = new Publisher('NotificationPublisher');\r\n\r\n$email = new Observer('EmailObserver', 50);\r\n$zoom = new Observer('ZoomObserver', 10);\r\n$dashboard = new Observer('DashboardObserver',30);\r\n\r\n\/\/ Attach observers$noty-&gt;attach($email);\r\n$noty-&gt;attach($zoom);\r\n$noty-&gt;attach($dashboard);\/\/ Set event that will be broadcasted\r\n$noty-&gt;setEvent(\"Server LNX109 is going down\");\r\n<\/pre>\n<h3>The Output<\/h3>\n<p>EmailObserver: Server LNX109 is going down<br \/>\nDashboardObserver: Server LNX109 is going down<br \/>\nZoomObserver: Server LNX109 is going down<\/p>\n<h2><span class=\"ez-toc-section\" id=\"what-are-the-pros-and-cons-of-observer-design-pattern\"><\/span>What are the Pros and Cons of Observer Design Pattern?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3>Pros \u2013<\/h3>\n<p>i) Observable (subject) and observers (objects) are loosely coupled. This lets you reuse the two independently of each other. For instance, you can make as many changes as you want to the observers without having to modify too many things.<\/p>\n<p>ii) Makes your code maintainable, reusable, scalable and the development process faster and cheaper, especially if you <a href=\"https:\/\/eluminoustechnologies.com\/hire-developers\/dedicated\/\" target=\"_blank\" rel=\"noopener\">hire dedicated resources<\/a> for the task.<\/p>\n<h3>Cons \u2013<\/h3>\n<p>i) If observer is wrongly implemented, it can increase complexity and cause unintended performance issues.<\/p>\n<p>ii) It can lead to memory leaks if the observer fails to detach from the subject when it no longer wants to receive notifications, aka, the Lapsed Listener Problem.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"when-to-use-observer-design-pattern\"><\/span>When to Use Observer Design Pattern?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Your <a href=\"https:\/\/eluminoustechnologies.com\/hire-developers\/dedicated\/\" target=\"_blank\" rel=\"noopener\">dedicated development team<\/a> can consider using observer design pattern when,<br \/>\ni) the change in state of one object must be reflected in the state of another object while keeping the two objects loosely coupled<\/p>\n<p>ii) the code needs to be enhanced in the future by adding new observers while keeping changes to the minimum.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"summing-it-up\"><\/span>Summing It Up<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>\u201cObserver pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically\u201d &#8211; Gang of Four<br \/>\nThis aspect of observer design pattern makes it an ideal choice for use in eCommerce stores, news feeds, live chats, social media (now you know how notifications work on Twitter, Facebook, and YouTube). It provides an organized and proven design for applications where several objects are dependent on the state of one object.<\/p>\n<p>As an IT business solution provider for almost 20 years, we\u2019ve used observer design patterns to build robust and scalable software quickly. This has helped our clients save money and time while effectively responding to dynamic market conditions and user preferences. If your business is faced with a similar challenge, get in touch with our <a href=\"https:\/\/eluminoustechnologies.com\/hire-developers\/dedicated\/\" target=\"_blank\" rel=\"noopener\">dedicated development team<\/a> now.<br \/>\nThank you for reading! If you liked this post, subscribe to our blog and get informative posts delivered straight to your inbox. We cover diverse topics on our blog including web and mobile development, data analytics, business intelligence, and eCommerce.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Software design patterns are tried and tested solutions to problems that developers commonly face while creating software. If you\u2019d like an in-depth explanation of software&#8230;<\/p>\n","protected":false},"author":7,"featured_media":2976,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[155],"tags":[312,326,325,324,335,327],"class_list":["post-2975","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-app-development-company","tag-dedicated-development-team","tag-hire-dedicated-resources","tag-it-business-solution-provider","tag-observer-design-pattern","tag-software-design-patterns"],"acf":[],"_links":{"self":[{"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/posts\/2975","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/comments?post=2975"}],"version-history":[{"count":2,"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/posts\/2975\/revisions"}],"predecessor-version":[{"id":24610,"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/posts\/2975\/revisions\/24610"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/media\/2976"}],"wp:attachment":[{"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/media?parent=2975"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/categories?post=2975"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/eluminoustechnologies.com\/blog\/wp-json\/wp\/v2\/tags?post=2975"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}