DEV Community

Iyanu Falaye
Iyanu Falaye

Posted on

Design Patterns: Observer

Observer pattern is a behavioral pattern where an object is observed by one or more dependents. the object is known as a subject and the dependents are the observers. It is based on the publish-subscribe pattern. It allows for a subscription mechanism that allows many objects to listen and react to changes in another object.

Motivation
The need to use observer patterns to ensure that the single responsibility principle is adhered to. It allows objects to be loosely coupled where objects don't need to know their dependents.

Implementation
In a social media application, we want to notify a user's friends whenever the user updates their profile picture so that friends can view and react to the new profile picture.
ProfileObserver is the Observer interface with a method to update the profile picture.

public interface PictureObserver {
    void updatePicture(String newProfilePicture);
}
Enter fullscreen mode Exit fullscreen mode

WhatsApp is an interface with methods to add, remove, and notify friends.

public interface WhatsApp {
    void addFriend(PictureObserver observer);
    void removeFriend(PictureObserver observer);
    void notifyFriends();
}
Enter fullscreen mode Exit fullscreen mode

UserWhatsApp is the ConcreteSubject. It maintains a list of friends and notifies them when the profile picture changes.

public class UserWhatsApp implements WhatsApp {
    private final List<PictureObserver> friends = new ArrayList<>();
    private String profilePicture = "default.jpg";

    public void setProfilePicture(String profilePicture) {
        this.profilePicture = profilePicture;
        notifyFriends();
    }

    @Override
    public void addFriend(PictureObserver observer) {
        friends.add(observer);
    }

    @Override
    public void removeFriend(PictureObserver observer) {
        friends.remove(observer);
    }

    @Override
    public void notifyFriends() {
        for(PictureObserver friend : friends) {
            friend.updatePicture(profilePicture);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

WhatsAppFriend Represents a friend who observes changes in the user profile. When notified of a change, it prints a message indicating that the friend has noticed the new profile picture.

public class WhatsAppFriend implements PictureObserver{
    private final String name;

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

    @Override
    public void updatePicture(String newProfilePicture) {
        System.out.println(name + " noticed that the profile picture has been updated to " + newProfilePicture);
    }
}
Enter fullscreen mode Exit fullscreen mode

We created a UserWhatsApp and two Friend observers then we added the friends as observers to the UserWhatsApp.
when the user updates the profile picture, the friends will be notified and a message will be printed.

UserWhatsApp user = new UserWhatsApp();
        WhatsAppFriend john = new WhatsAppFriend("John");
        WhatsAppFriend cathy = new WhatsAppFriend("Cathy");

        user.addFriend(john);
        user.addFriend(cathy);
        user.setProfilePicture("new_picture.jpg");

        user.removeFriend(john);
        WhatsAppFriend peter = new WhatsAppFriend("Peter");
        user.addFriend(peter);

        user.setProfilePicture("new_picture2.jpg");
Enter fullscreen mode Exit fullscreen mode

The user added John and Cathy and they were notified when the user changed the profile picture.

John noticed that the profile picture has been updated to new_picture.jpg
Cathy noticed that the profile picture has been updated to new_picture.jpg
Enter fullscreen mode Exit fullscreen mode

Then the user removed john as his friend and added peter then updated his profile picture. only Cathy and Peter are going to be notified of the profile picture change this time.

Cathy noticed that the profile picture has been updated to new_picture2.jpg
Peter noticed that the profile picture has been updated to new_picture2.jpg
Enter fullscreen mode Exit fullscreen mode

Advantages

  1. It supports the principle of loose coupling between objects.
  2. It allows an efficient way to send data to dependents without any change in the subject and the observers.

Disadvantages

  1. It can lead to complexity.

Use cases

  1. Live data in Android.
  2. GUI libraries.

Conclusion
The Observer Pattern is a tool that champions code reusability and abstraction. It is widely used, easy to implement, and highly effective in achieving a separation of concerns in object-oriented software design.

Top comments (0)