{"id":4973,"date":"2024-02-24T16:32:17","date_gmt":"2024-02-24T16:32:17","guid":{"rendered":"https:\/\/codethataint.com\/blog\/?p=4973"},"modified":"2024-02-25T04:56:05","modified_gmt":"2024-02-25T04:56:05","slug":"observer-pattern","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/observer-pattern\/","title":{"rendered":"Observer Pattern"},"content":{"rendered":"<blockquote><p>\nThe Observer 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. The observer pattern is a behavioral design pattern that defines a one-to-many relationship between objects. It allows an object, called the subject, to notify other objects, called observers, about any changes in its state. The observers can then react to these changes according to their own logic.\n<\/p><\/blockquote>\n<p><strong class=\"ctaHeader3\">Why Observer Design Pattern<\/strong><br \/>\nThe subject and the observers are loosely coupled, meaning that they do not depend on each other&#8217;s implementation details. The subject only knows that it has a list of observers, and the observers only know that they can update themselves when the subject changes.<\/p>\n<p><strong class=\"ctaHeader3\">When Observer Design  Pattern <\/strong><br \/>\nThe observer pattern is especially useful in event-driven systems, where the system reacts to events that occur asynchronously. An event is a change in the state of the system or its components, such as a user input, a network request, or a timer. Use the pattern when some objects in your app must observe others, but only for a limited time or in specific cases. Use the Observer pattern when changes to the state of one object may require changing other objects, and the actual set of objects is unknown beforehand or changes dynamically.<\/p>\n<p><strong class=\"ctaHeader3\">How Observer Design Pattern<\/strong><\/p>\n<ol>\n<li>Declare the subscriber interface(IObserver.java). At a bare minimum, it should declare a single update method.<\/li>\n<li>Declare the publisher interface(Observable.java) and describe a pair of methods for adding a subscriber(Observer) object to and removing it from the list. Remember that publishers must work with subscribers only via the subscriber interface.<\/li>\n<li>Create concrete publisher classes. Each time something important happens inside a publisher, it must notify all its subscribers.<\/li>\n<li>Implement the update notification methods in concrete subscriber classes. Most subscribers would need some context data about the event. It can be passed as an argument of the notification method.<\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2024\/02\/ObserverPatternBasic.png\" alt=\"\" \/><\/p>\n<p><strong>IObserver.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic interface IObserver {\r\n    public void notify(String serviceName);\r\n}\r\n<\/pre>\n<p><strong>Observer.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Observer implements IObserver {\r\n    @Override\r\n    public void notify(String serviceName) {\r\n            System.out.println(&quot;Notification from &quot; + serviceName);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Observable.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Observable {\r\n    private List&lt;IObserver&gt; observers = new ArrayList&lt;IObserver&gt;();\r\n\r\n    public void addObserver(IObserver observer){\r\n        this.observers.add(observer);\r\n    }\r\n\r\n    public void execute(){\r\n        for (IObserver observer : observers) {\r\n            observer.notify(&quot;Email Service&quot;);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Client.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Client {\r\n    public static void main(String&#x5B;] args) {\r\n        Observable observable = new Observable();\r\n        observable.addObserver(new Observer());\r\n        observable.execute();\r\n    }\r\n}\r\n<\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2024\/02\/SeqDiagramObserver.png\" alt=\"\" \/><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2024\/02\/ObserverPattern2.png\" alt=\"\" \/><\/p>\n<p><strong>IObserver.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic interface IObserver {\r\n    public void notify(String foodItem);\r\n}\r\n<\/pre>\n<p><strong>DeliveryOrderObserver.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class DeliveryOrderObserver implements IObserver {\r\n    @Override\r\n    public void notify(String foodItem) {\r\n        System.out.println(&quot;Ready for Pickup - &quot;+ foodItem);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>FoodOrderObserver.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class FoodOrderObserver implements IObserver {\r\n    @Override\r\n    public void notify(String foodItem) {\r\n        System.out.println(&quot; Order received - &quot;+ foodItem);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>FoodPickUpObserver.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class FoodPickUpObserver implements IObserver {\r\n    @Override\r\n    public void notify(String foodItem) {\r\n        System.out.println(&quot;Parcel - &quot;+ foodItem);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>PrepareFoodObserver.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class PrepareFoodObserver implements IObserver {\r\n    @Override\r\n    public void notify(String foodItem) {\r\n        System.out.println(&quot;Preparing - &quot;+ foodItem);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Observable.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Observable {\r\n    private List&lt;IObserver&gt; observers = new ArrayList&lt;IObserver&gt;();\r\n\r\n    public void addObserver(IObserver observer){\r\n        this.observers.add(observer);\r\n    }\r\n\r\n    public void execute(){\r\n            for(IObserver observer: observers){\r\n                observer.notify(&quot;Egg Biryani&quot;);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><strong>FoodAppClient.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class FoodAppClient {\r\n    public static void main(String&#x5B;] args) {\r\n        Observable observable = new Observable();\r\n\r\n        observable.addObserver(new FoodOrderObserver());\r\n        observable.addObserver(new PrepareFoodObserver());\r\n        observable.addObserver(new FoodPickUpObserver());\r\n        observable.addObserver(new DeliveryOrderObserver());\r\n        observable.execute();\r\n    }\r\n}\r\n<\/pre>\n<pre>\r\nOrder received - Egg Biryani\r\nPreparing - Egg Biryani\r\nParcel - Egg Biryani\r\nReady for Pickup - Egg Biryani\r\n<\/pre>\n<p><strong  class=\"ctaHeader3\">Advantages of Observer Pattern<\/strong><\/p>\n<ol>\n<li>The subject and the observers can be reused in different contexts, as long as they implement the common interface. The subject does not need to know the details of the observers, and the observers do not need to know the details of the subject. The subject and the observers can be added, removed, or changed at runtime, without affecting the rest of the system.<\/li>\n<li>The subject can notify the observers asynchronously, without waiting for their responses. The observers can process the events in parallel, without blocking the subject. This allows for the subject and the observers to adapt to changing requirements and scenarios.<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>The Observer 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. The observer pattern is a behavioral design pattern that defines a one-to-many relationship between objects. It allows an object, called the subject, to notify other objects, called observers, about any&hellip; <a href=\"https:\/\/codethataint.com\/blog\/observer-pattern\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[361],"tags":[],"class_list":["post-4973","post","type-post","status-publish","format-standard","hentry","category-observer-pattern"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4973","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=4973"}],"version-history":[{"count":5,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4973\/revisions"}],"predecessor-version":[{"id":4985,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/4973\/revisions\/4985"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=4973"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=4973"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=4973"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}