• Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
Thursday, July 30, 2026
No Result
View All Result
Subscribe Now
  • Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
    TX Rep. Brandon Gill Mocks James Talarico Over Fauci Action Figure Post

    TX Rep. Brandon Gill Mocks James Talarico Over Fauci Action Figure Post

    NBA players are ‘being taught’ to flop

    NBA players are ‘being taught’ to flop

    Industry was warned for years about chemical ‘runaway’ dangers. Then came near-catastrophe in O.C.

    Industry was warned for years about chemical ‘runaway’ dangers. Then came near-catastrophe in O.C.

    Trump administration seeks government-wide NDAs to stop leaks : NPR

    Trump administration seeks government-wide NDAs to stop leaks : NPR

    Dog discharges shotgun inside truck, striking woman at Nebraska traffic light

    Dog discharges shotgun inside truck, striking woman at Nebraska traffic light

    Toshifumi Suzuki, Japan’s ‘God’ of Convenience Stores, Dies at 93

    Toshifumi Suzuki, Japan’s ‘God’ of Convenience Stores, Dies at 93

     Judge Sanctioned CoreCivic for Destroying Video in ICE Death Suit

     Judge Sanctioned CoreCivic for Destroying Video in ICE Death Suit

    Suspect dead after opening fire near White House security checkpoint, Secret Service says

    Suspect dead after opening fire near White House security checkpoint, Secret Service says

    Trump trashes Colbert’s high-rated finale as “no ratings”

    Trump trashes Colbert’s high-rated finale as “no ratings”

  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
The Insight Post
  • Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
    TX Rep. Brandon Gill Mocks James Talarico Over Fauci Action Figure Post

    TX Rep. Brandon Gill Mocks James Talarico Over Fauci Action Figure Post

    NBA players are ‘being taught’ to flop

    NBA players are ‘being taught’ to flop

    Industry was warned for years about chemical ‘runaway’ dangers. Then came near-catastrophe in O.C.

    Industry was warned for years about chemical ‘runaway’ dangers. Then came near-catastrophe in O.C.

    Trump administration seeks government-wide NDAs to stop leaks : NPR

    Trump administration seeks government-wide NDAs to stop leaks : NPR

    Dog discharges shotgun inside truck, striking woman at Nebraska traffic light

    Dog discharges shotgun inside truck, striking woman at Nebraska traffic light

    Toshifumi Suzuki, Japan’s ‘God’ of Convenience Stores, Dies at 93

    Toshifumi Suzuki, Japan’s ‘God’ of Convenience Stores, Dies at 93

     Judge Sanctioned CoreCivic for Destroying Video in ICE Death Suit

     Judge Sanctioned CoreCivic for Destroying Video in ICE Death Suit

    Suspect dead after opening fire near White House security checkpoint, Secret Service says

    Suspect dead after opening fire near White House security checkpoint, Secret Service says

    Trump trashes Colbert’s high-rated finale as “no ratings”

    Trump trashes Colbert’s high-rated finale as “no ratings”

  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
No Result
View All Result
No Result
View All Result
Home Tech

Intro to the Observable design pattern

by Theinsightpost
December 20, 2022
in Tech
0 0
0
Intro to the Observable design pattern


The Observable design pattern is used in many important Java APIs. One well-known example is a JButton that uses the ActionListener API to execute an action. In this example, we have an ActionListener listening or observing on the button. When the button is clicked, the ActionListener performs an action.

The Observable pattern is also used with reactive programming. The use of observers in reactive applications makes sense because the essence of reactive is reaction: something happens when another process occurs.

Observable is a behavioral design pattern. Its function is to perform an action when an event happens. Two common examples are button clicks and notifications, but there are many more uses for this pattern.

An example of the Observable pattern

In the Observable pattern, one object notifies another object when an action is performed. To appreciate the value of the pattern, let’s imagine a scenario where a button needs to be clicked and there is no notification to another object, as shown in Figure 1.

Diagram of the Observable design pattern. IDG

Figure 1. ActionCheck checks the button once per second.

Notice that the ActionCheck has to check the button once per second. Now, imagine if we had multiple action checks for this button every second. Can you imagine what that would do to your application performance?

It’s much easier to let the Do Something button notify the ActionCheck. This way, the ActionCheck logic does not need to poll the Do Something button every second.

Elements of the Observable design pattern

In the following diagram, notice that the basis of the Observer pattern are the Observer interface (that is, the object that observes) and the Subject (the object that is being observed). The Newsletter class implements Subject and the Subscriber implements Observer. Then, finally, the SendEmailMain executes the Observable design pattern.

A diagram of the Observable design pattern. IDG

Figure 2. The flow of the Observable design pattern in a subscriber example.

The Observable pattern in code

The Subject interface, also known as Observable or Publisher, is the basis of the Observable design pattern. Basically, it stores observers and notifies them as soon as a watched action happens. Have a look at the Subject interface.


public interface Subject {

    void addSubscriber(Observer observer);
    void removeSubscriber(Observer observer);
    void notifySubscribers();

}

The Observer interface

The Observer interface (also sometimes known as the Subscriber) is implemented by subscriber, which seeks to observe whether an action has been performed:


public interface Observer {

    public void update(String email);

}

Observable in action

Let’s use an example of a newsletter to implement the Subject interface. In the following code, we store our observers—in this case, newsletter subscribers—and each subscriber is notified when their email is added to the subscriptions.


import java.util.ArrayList;
import java.util.List;

public class Newsletter implements Subject {

    protected List<Observer> observers = new ArrayList<>();
    protected String name;
    protected String newEmail;

    public Newsletter(String name) {
        this.name = name;
    }

    public void addNewEmail(String newEmail) {
        this.newEmail = newEmail;
        notifySubscribers();
    }

    @Override
    public void addSubscriber(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeSubscriber(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifySubscribers() {
        observers.forEach(observer -> observer.update(newEmail));
    }
}

Subscriber

The Subscriber class represents the user who subscribes to the email newsletter. This class implements the Observer interface. It is the object we will observe so that we know if an event has happened.


class Subscriber implements Observer {

  private String name;

  public Subscriber(String name) {
    this.name = name;
  }

  @Override
  public void update(String newEmail) {
    System.out.println("Email for: " + name + " | Content:" + newEmail);
  }

}

SendEmailMain

Now we have the main class that will make the Observable pattern effectively work. First, we will create the Newsletter object. Then, we will add and remove subscribers. Finally, we will add an email and notify the subscriber of their status.


public class SendEmailMain {

  public static void main(String[] args) {
    Newsletter newsLetter = new Newsletter("Java Challengers");

    Observer duke = new Subscriber("Duke");
    Observer juggy = new Subscriber("Juggy");
    Observer dock = new Subscriber("Moby Dock");

    newsLetter.addSubscriber(duke);
    newsLetter.addNewEmail("Lambda Java Challenge");
    newsLetter.removeSubscriber(duke);

    newsLetter.addSubscriber(juggy);
    newsLetter.addSubscriber(dock);
    newsLetter.addNewEmail("Virtual Threads Java Challenge");
  }

}

Here is the output from our code:


Email for: Duke | Content:Lambda Java Challenge
Email for: Juggy | Content:Virtual Threads Java Challenge
Email for: Moby Dock | Content:Virtual Threads Java Challenge

When to use the Observable pattern

When an action happens and multiple objects need to be notified, it’s better to use the Observable pattern rather than checking the state of an Object many times. Imagine that more than 200 objects needing to receive a notification; in that case, you would have to multiply 200 by the number of times the check would happen.

By using the Observable pattern, the notification would happen only once to all of your subscribers. It’s a huge performance gain as well as being an effective code optimization. This code can easily be extended or changed.

The reactive programming paradigm uses the Observable pattern everywhere. If you ever worked with Angular, then you will know that using Observable components is very common. Reactive components are frequently observed by other events and logic, and when a certain condition is fulfilled, the component will execute some action.

Conclusion

Here are the important points to remember about the Observable design pattern:

  • Observable uses the open-closed SOLID principle. This means that we can extend the addSubscriber and removeSubscriber methods without needing to change the method signature. The reason is that it received the Subject interface instead of a direct implementation.
  • The Observer interface observes any action that happens on the Subject.
  • The Subject is also called the Observable because it’s a subject that will be observed. It may also be known as the Publisher because it publishes events.
  • The Observer is also called the Subscriber because it subscribes to the Subject/Publisher. The Observer is notified when an action happens.
  • If we did not use the Observable design pattern, the Subscriber would have to constantly poll to know whether an event had happened, which could be horrible for your application performance. Observable is a more efficient solution.

Copyright © 2022 IDG Communications, Inc.



Source link

ShareTweetSend
Previous Post

Northern California earthquake near Ferndale: Outages reported

Next Post

Authorities tip the bucket on hooligans for A-League pitch invasion

Related News

A fundamental flaw leaves LLMs strikingly vulnerable to attack
Tech

A fundamental flaw leaves LLMs strikingly vulnerable to attack

July 30, 2026
Google engineer charged with insider trading after making .2M on Polymarket
Tech

Google engineer charged with insider trading after making $1.2M on Polymarket

May 27, 2026
The Osprey Farpoint 40 Has Been My Go-To Travel Bag for 8 Years
Tech

The Osprey Farpoint 40 Has Been My Go-To Travel Bag for 8 Years

May 27, 2026
Source: AI inference provider Baseten is in talks to raise B at a post-money valuation of B, up from B after its 0M Series E announced in January (The Information)
Tech

Source: AI inference provider Baseten is in talks to raise $1B at a post-money valuation of $11B, up from $5B after its $300M Series E announced in January (The Information)

May 26, 2026
Next Post
Authorities tip the bucket on hooligans for A-League pitch invasion

Authorities tip the bucket on hooligans for A-League pitch invasion

Discussion about this post

Subscribe To Our Newsletters

    Customer Support


    1251 Wilcrest Drive
    Houston, Texas
    77042 USA
    Call-832.795.1420
    e-mail – news@theinsightpost.com

    Subscribe To Our Newsletters

      Categories

      • Africa
      • Africa-East
      • African Sports
      • American Sports
      • Arts
      • Asia
      • Australia
      • Business
      • Business Asia
      • Business- Africa
      • Canada
      • Defense
      • Education
      • Egypt
      • Energy
      • Entertainment
      • Europe
      • European Soccer
      • Finance
      • Germany
      • Ghana
      • Health
      • Insight
      • International
      • Investing
      • Japan
      • Latest Headlines
      • Life & Living
      • Markets
      • Mobile
      • Movies
      • New Zealand
      • Nigeria
      • Politics
      • Scholarships
      • Science
      • South Africa
      • South America
      • Sports
      • Tech
      • Travel
      • UK
      • USA
      • Weather
      • World
      No Result
      View All Result

      Recent News

      Free Cloud Computing Course | AWS Re/Start Program 

      Free Cloud Computing Course | AWS Re/Start Program 

      July 30, 2026
      Thirty Years Later

      Thirty Years Later

      July 30, 2026
      Announcing Codemagic Patch: an open-source CodePush rebuild for React Native

      Announcing Codemagic Patch: an open-source CodePush rebuild for React Native

      July 30, 2026
      Following Expansion in China, Regional Private Equity Faces New Scrutiny in Southeast Asia – The Diplomat

      Following Expansion in China, Regional Private Equity Faces New Scrutiny in Southeast Asia – The Diplomat

      July 30, 2026
      • Home
      • Advertise With Us
      • About Us
      • Corporate
      • Consumer Rewards
      • Forum
      • Privacy Policy
      • Social Trends

      Theinsightpost ©2026 | All Rights Reserved. Theinsightpost is an Elnegy LLC company, registered in Texas, USA

      Welcome Back!

      Login to your account below

      Forgotten Password?

      Retrieve your password

      Please enter your username or email address to reset your password.

      Log In

      Add New Playlist

      We are using cookies to give you the best experience on our website.

      You can find out more about which cookies we are using or switch them off in .

      No Result
      View All Result
      • Home
      • Insight
      • Blog
      • Business
      • Entertainment
      • Health
      • Politics
      • Shop
        • Gift Shop
        • Value Shop
        • Store
        • Bargain Shop
        • Discount
      • Sports
      • Tech
      • Travel
      • USA
      • Video
      • World
        • Asia
        • Africa
        • South America
        • North America
        • Europe
        • Oceania

      Theinsightpost ©2026 | All Rights Reserved. Theinsightpost is an Elnegy LLC company, registered in Texas, USA

      The Insight Post
      Powered by  GDPR Cookie Compliance
      Privacy Overview

      This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

      Strictly Necessary Cookies

      Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

      Cookie Policy

      More information about our Cookie Policy