{"id":2984,"date":"2024-02-12T16:05:47","date_gmt":"2024-02-12T16:05:47","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=2984"},"modified":"2025-07-07T10:57:25","modified_gmt":"2025-07-07T10:57:25","slug":"java-observer","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-observer\/","title":{"rendered":"Java design pattern Observer"},"content":{"rendered":"<p>Today we will look at another <strong>Java<\/strong> <strong>design pattern<\/strong> from the category of <strong>behavioural patterns<\/strong> &#8211; Observer. Design patterns in this category deal with the <strong>interaction<\/strong> between objects and their <strong>responsibility<\/strong>. <\/p>\n<h2>What is the Observer design pattern?<\/h2>\n<p><strong>Observer<\/strong> is a design pattern that allows us to define a mechanism for taking messages and notifying all interested objects of any events that occur on the observed object. <\/p>\n<h2>What problem does the Observer design pattern solve?<\/h2>\n<p> The <strong>Observer <\/strong> pattern is a design pattern that solves the problem of tracking a change in the state of an object so that all of its dependent objects (observers) are automatically notified and updated when the object changes. This pattern allows to establish weak ties between the subject (the object that changes its state) and the observers (the objects that want to be informed about the change). The observed object &#8211; <strong>Publisher <\/strong> undergoes events of interest to other objects. These events occur when it changes its state or performs an action. Publishers contain a subscription infrastructure that allows new <strong>subscribers <\/strong> to join and existing subscribers to leave the list. When a new event occurs, the publisher traverses the subscription list and calls the notification method declared in the subscriber interface on each subscriber object. In most cases, the subscriber interface consists of a single update method. The method may have several parameters that allow the Publisher to report more detailed information about the event along with the update. Specific Subscribers take their own actions in response to notifications issued by the Publisher. All these classes must implement the same interface, so the Publisher is not directly linked to specific classes. Subscribers usually require contextual information in order to process the update correctly. The client creates publisher and subscriber objects separately, and then registers subscribers for publisher updates.            <\/p>\n<h2>Example of an Observer implementation in Java<\/h2>\n<p> To demonstrate a practical application of the <strong>Observer <\/strong> design pattern, we create a simple simulation of a YouTube channel where users (subscribers) can subscribe or unsubscribe to receive notifications about new videos on the channel. <strong><u>ISubscriber.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic interface IOdoberatel {\n    void aktualizovat(String sprava);\n}<\/code><\/pre>\n<p> The <strong>ISubscriber<\/strong> interface defines the update method that specific subscribers will implement. It is used to update in case of new content. <strong><u>YouTubeUser.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class YouTubePouzivatel implements IOdoberatel {\n    private String meno;\n\n    public YouTubePouzivatel(String meno) {\n        this.meno = meno;\n    }\n\n    @Override\n    public void aktualizovat(String videoTitul) {\n        System.out.println(meno + &quot; dostal\/a notifik\u00e1ciu o novom videu: &quot; + videoTi-tul);\n    }\n\n    @Override\n    public String toString() {\n        return meno;\n    }\n}\n<\/code> Trieda <strong>YouTubePouzivatel <\/strong>reprezentuje konkr\u00e9tneho pou\u017e\u00edvate\u013ea, ktor\u00fd m\u00f4\u017ee prij\u00edma\u0165 notifik\u00e1cie o nov\u00fdch vide\u00e1ch.<\/pre>\n<p><span style=\"text-decoration: underline;\"><strong>IYoutubeChannel.java<\/strong><\/span><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic interface IYoutubeKanal {\n    void odoberat(IOdoberatel odoberatel);\n    void zrusitOdber(IOdoberatel odoberatel);\n    void upozornitOdoberatelov(String videoTitul);\n}<\/code><\/pre>\n<p> The <strong>IYoutubeChannel<\/strong> interface defines the subscribe, deleteSubscription and notifySubscriber methods that a particular YouTube channel will implement. It is used to manage subscribers. <strong><u>YouTubeChannel.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class YouTubeKanal implements IYoutubeKanal {\n    private List&lt;IOdoberatel&gt; odoberatelia = new ArrayList&lt;&gt;();\n    private String nazovKanala;\n\n    public YouTubeKanal(String nazovKanala) {\n        this.nazovKanala = nazovKanala;\n    }\n\n    @Override\n    public void odoberat(IOdoberatel odoberatel) {\n        odoberatelia.add(odoberatel);\n        System.out.println(odoberatel + &quot; odober\u00e1 &quot; + nazovKanala);\n    }\n\n    @Override\n    public void zrusitOdber(IOdoberatel odoberatel) {\n        odoberatelia.remove(odoberatel);\n        System.out.println(odoberatel + &quot; odhl\u00e1sil\/a odber &quot; + nazovKanala);\n    }\n\n    @Override\n    public void upozornitOdoberatelov(String videoTitul) {\n        for(IOdoberatel odoberatel : odoberatelia) {\n            odoberatel.aktualizovat(videoTitul);\n        }\n    }\n\n    public void nahratNoveVideo(String videoTitul) {\n        System.out.println(&quot;Nov\u00e9 video bolo pridan\u00e9: &quot; + videoTitul);\n        upozornitOdoberatelov(videoTitul);\n    }\n}<\/code><\/pre>\n<p> The <strong>YouTubeChannel<\/strong> class represents a specific YouTube channel that can subscribe and unsubscribe subscribers and notify them of new videos. <strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.IOdoberatel;\nimport designpatterns.IYoutubeKanal;\nimport designpatterns.YouTubeKanal;\nimport designpatterns.YouTubePouzivatel;\n\npublic class Main {\n    public static void main(String[] args) {\n        \/\/ Vytvorenie YouTube kanalu\n        YouTubeKanal youtubeKanal = new YouTubeKanal(&quot;[Programovanie v Jave]&quot;);\n\n        \/\/ Vytvorenie odoberatelov (subscribers)\n        IOdoberatel odoberatel1 = new YouTubePouzivatel(&quot;Subscriber1&quot;);\n        IOdoberatel odoberatel2 = new YouTubePouzivatel(&quot;Subscriber2&quot;);\n\n        \/\/ Nastavenie odberov YouTube kanala\n        youtubeKanal.odoberat(odoberatel1);\n        youtubeKanal.odoberat(odoberatel2);\n\n        \/\/ Pridanie noveho videa, vsetci odoberatelia dostanu upozornenie\n        youtubeKanal.nahratNoveVideo(&quot;Navrhove vzory v Jave&quot;);\n\n        \/\/ Odoberatel 1 odhlasi odber\n        youtubeKanal.zrusitOdber(odoberatel1);\n\n        \/\/ Pridanie dalsieho videa, notifikaciu dostatne len Odoberatel 2\n        youtubeKanal.nahratNoveVideo(&quot;Java SDK 21&quot;);\n    }\n}<\/code><\/pre>\n<p> The <strong>Main <\/strong> class simulates the operation of a single YouTube channel where users (subscribers) can subscribe and when a new video is added, all subscribers are notified.  Also note that if a user unsubscribes, they will no longer receive notifications about new content. The output of this example is: &nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-2752 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-observer-750-330.webp\" alt=\"The output of the Observer design pattern example.\" width=\"750\" height=\"330\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-observer-750-330.webp 750w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/vystup-z-prikladu-observer-750-330-300x132.webp 300w\" sizes=\"auto, (max-width: 750px) 100vw, 750px\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p> The <strong>Observer <\/strong> pattern is used in systems that process events, e.g. in GUI components (mouse click on a button), but it is also useful wherever we want to react flexibly to a change in the observed object.  We have prepared the files with the above example in the form of code that you can run directly in Java. You can download <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/02\/Observer.zip\">the Java <strong>Observer<\/strong> code here.<\/a> If you&#8217;re looking for a job and you&#8217;re a <a href=\"https:\/\/msg-life.sk\/en\/jobs\/java-programmer-senior\/\">Java developer<\/a>, check out our <a href=\"https:\/\/msg-life.sk\/en\/benefits\/\">employee benefits<\/a> and respond to our latest <a href=\"https:\/\/msg-life.sk\/en\/jobs\/\">job offers<\/a>! &nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is the Java Observer design pattern and what is it for? Read our new article and download the sample code.<\/p>\n","protected":false},"author":14,"featured_media":2756,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-2984","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2984","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=2984"}],"version-history":[{"count":7,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2984\/revisions"}],"predecessor-version":[{"id":5275,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2984\/revisions\/5275"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/2756"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=2984"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=2984"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=2984"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}