Home Java javaTutorial Observer Pattern

Observer Pattern

Nov 03, 2024 pm 11:41 PM

What is Observer Pattern?

Observer pattern is a behavioral pattern that 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 object changes state is called Subject, and its dependents are called Observers.

When to use it?

You can use Observer pattern when you need one-to-many dependency between objects, the one will change its state and the many dependents need to keep track of those changes.

Let's assume we use SNS like X(Twitter), companies and people have their own account, and people can follow their favorite company so that they want notification when the company post about new item or sale item. In this situation, Observer pattern is applicable.

UML diagram

Observer Pattern

Example UML diagram

Observer Pattern

  • When setSaleItem method is called, that is, the state is changed, we call setItemChanged method. Then, setItemChanged method calls notifyAccount method.
  • notifyAccount method in Company class iterates each follower and call update method with its own Company object such as follower.update(this)

Implementation in Java

ICompany interface:

public interface ICompany {

    void registerAccount(IAccount account);

    void removeAccount(IAccount account);

    void notifyAccounts();
}

Company class:

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

public class Company implements ICompany {

    private List<IAccount> followers;

    private String name;

    private String saleItem;

    public Company(String name) {
        followers = new ArrayList<>();
        this.name = name;
    }

    @Override
    public void registerAccount(IAccount account) {
        this.followers.add(account);
    }

    @Override
    public void removeAccount(IAccount account) {
        this.followers.remove(account);
    }

    @Override
    public void notifyAccounts() {
        for (IAccount follower : followers) {
            follower.update(this);
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSaleItem() {
        return saleItem;
    }

    public void setSaleItem(String saleItem) {
        this.saleItem = saleItem;
        saleItemChanged();
    }

    public void saleItemChanged() {
        notifyAccounts();
    }
}

IAccount interface:

public interface IAccount {

    void update(Company company);
}

Account class:

public class Account implements IAccount {

    private String name;

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

    @Override
    public void update(Company company) {
        System.out.println(this.name + " receives a new message from " + company.getName());
        System.out.println("New sale item: " + company.getSaleItem());
    }
}

Client class:

public class Client {

    public static void main(String[] args) {
        Company apple = new Company("Apple"); // concrete subject

        IAccount john = new Account("John");
        IAccount david = new Account("David");

        // John starts following Apple Inc.
        apple.registerAccount(john);
        apple.setSaleItem("iPhone 14");
        System.out.println("**********************");

        // David becomes a new follower to Apple Inc.
        apple.registerAccount(david);
        apple.setSaleItem("iPad");
        System.out.println("**********************");

        // John doesn't receive message from Apple Inc. as he deregistered for Apple Inc.
        apple.removeAccount(john);
        apple.setSaleItem("AirPods");
    }
}

Output:

John receives a new message from Apple
New sale item: iPhone 14
**********************
John receives a new message from Apple
New sale item: iPad
David receives a new message from Apple
New sale item: iPad
**********************
David receives a new message from Apple
New sale item: AirPods

You can check all the design pattern implementations here.
GitHub Repository


P.S.
I'm new to write tech blog, if you have advice to improve my writing, or have any confusing point, please leave a comment!
Thank you for reading :)

The above is the detailed content of Observer Pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to add a JAR file to the classpath in Java? How to add a JAR file to the classpath in Java? Sep 21, 2025 am 05:09 AM

Use the -cp parameter to add the JAR to the classpath, so that the JVM can load its internal classes and resources, such as java-cplibrary.jarcom.example.Main, which supports multiple JARs separated by semicolons or colons, and can also be configured through CLASSPATH environment variables or MANIFEST.MF.

How to create a file in Java How to create a file in Java Sep 21, 2025 am 03:54 AM

UseFile.createNewFile()tocreateafileonlyifitdoesn’texist,avoidingoverwriting;2.PreferFiles.createFile()fromNIO.2formodern,safefilecreationthatfailsifthefileexists;3.UseFileWriterorPrintWriterwhencreatingandimmediatelywritingcontent,withFileWriterover

How to implement an interface in Java? How to implement an interface in Java? Sep 18, 2025 am 05:31 AM

Use the implements keyword to implement the interface. The class needs to provide specific implementations of all methods in the interface. It supports multiple interfaces and is separated by commas to ensure that the methods are public. The default and static methods after Java 8 do not need to be rewrite.

Building Extensible Applications with the Java Service Provider Interface (SPI) Building Extensible Applications with the Java Service Provider Interface (SPI) Sep 21, 2025 am 03:50 AM

JavaSPI is a built-in service discovery mechanism in JDK, and implements interface-oriented dynamic expansion through ServiceLoader. 1. Define the service interface and create a file with the full name of the interface under META-INF/services/, and write the fully qualified name of the implementation class; 2. Use ServiceLoader.load() to load the implementation class, and the JVM will automatically read the configuration and instantiate it; 3. The interface contract should be clarified during design, support priority and conditional loading, and provide default implementation; 4. Application scenarios include multi-payment channel access and plug-in verification; 5. Pay attention to performance, classpath, exception isolation, thread safety and version compatibility; 6. In Java9, provide can be used in combination with module systems.

A deep understanding of HTTP persistent connections: policies and practices for sending multiple requests on the same socket A deep understanding of HTTP persistent connections: policies and practices for sending multiple requests on the same socket Sep 21, 2025 pm 01:51 PM

This article explores in-depth the mechanism of sending multiple HTTP requests on the same TCP Socket, namely, HTTP persistent connection (Keep-Alive). The article clarifies the difference between HTTP/1.x and HTTP/2 protocols, emphasizes the importance of server-side support for persistent connections, and how to correctly handle Connection: close response headers. By analyzing common errors and providing best practices, we aim to help developers build efficient and robust HTTP clients.

Understanding Java Generics and Wildcards Understanding Java Generics and Wildcards Sep 20, 2025 am 01:58 AM

Javagenericsprovidecompile-timetypesafetyandeliminatecastingbyallowingtypeparametersonclasses,interfaces,andmethods;wildcards(?,?extendsType,?superType)handleunknowntypeswithflexibility.1.UseunboundedwildcardwhentypeisirrelevantandonlyreadingasObject

Java Tutorial: How to Flatten a Nested ArrayList and Fill its Elements into an Array Java Tutorial: How to Flatten a Nested ArrayList and Fill its Elements into an Array Sep 18, 2025 am 07:24 AM

This tutorial details how to efficiently process nested ArrayLists containing other ArrayLists in Java and merge all its internal elements into a single array. The article will provide two core solutions through the flatMap operation of the Java 8 Stream API: first flattening into a list and then filling the array, and directly creating a new array to meet the needs of different scenarios.

How to read a properties file in Java? How to read a properties file in Java? Sep 16, 2025 am 05:01 AM

Use the Properties class to read Java configuration files easily. 1. Put config.properties into the resource directory, load it through getClassLoader().getResourceAsStream() and call the load() method to read the database configuration. 2. If the file is in an external path, use FileInputStream to load it. 3. Use getProperty(key,defaultValue) to handle missing keys and provide default values ​​to ensure exception handling and input verification.

See all articles