Welcome to the world of software design patterns!
In the realm of coding, the Observer Design Pattern stands as a powerful tool for enhancing the flexibility and maintainability of your codebase. By providing a framework for communication between objects, this pattern helps you build adaptable and easy to maintain applications.
In this article, we will demystify the Observer Design Pattern, breaking it down into simple concepts, and showing you how it can revolutionize your code. We will explore the core principles behind this pattern, delve into its implementation, and provide you with practical examples to illustrate its effectiveness.
Whether you’re a seasoned programmer looking to level up your skills or a beginner seeking to build a solid foundation in software design, this article is for you.
By the end, you’ll have a deep understanding of :
So, let’s dive in and unlock the power of the Observer Design Pattern! Get ready to elevate your coding to a whole new level of elegance and efficiency.
The observer design pattern is proper when you are interested in the state of an object and want to get notified whenever there is any change. In the observer pattern, the object that watches the state of another object is called Observer and the object that is being watched is called Subject.
Let’s take a look at the real-life implementation of the Observer Design Pattern. A newsletter with sales and new products of the shop is the subject. All the subscribers in this newsletter are observers.
Every time a new product is added to the shop, the marketing sends a newsletter. It might include media, such as videos and photos of the product. The subscribers are notified about the new product.
In this example, the subscribers are observers, and the store is the subject.
Another example is YouTube.
Each YouTuber has many subscribers on their channel. Each subscriber wants to watch their subscribed channel’s videos. When a subscriber has an interest in a specific YouTuber’s channel, they subscribe to it. When they lose interest, they unsubscribe from the channel. At this point, we can think of subscribers as an observer and the YouTuber as the subject. So, if we start creating domains we should create a class that adds, deletes, or notifies all observers.
Moving ahead and implementing the Observer design pattern using Java. Java provides an in-built platform for implementing the Observer pattern through Java. util.Observable class and Java. util.Observer interface.
Observable classes are used to create subclasses that other parts of the program can observe. When an object of such subclass changes, observing classes are notified.
Let us implement an observer design pattern with the Shop Newsletter example. Subscribers can register themselves to get updates on any news of the Shop. In the same way, they can unsubscribe if they have no interest anymore. Subscribers are acting as Observers, and Store will act as a Subject.
Let’s assume that a store wants to notify its loyal customers of an ongoing sale. The system would send a short message to all subscribed customers whenever a sale has been activated.
In the pattern, the Observer is defined as a Java Interface.
public interface Observer { public void notification(String handle, String news); }
The Subject is also defined as a Java Interface, with methods that add, remove, and notify the observers.
public interface Subject { public void addSubscriber(Observer observer); public void removeSubscriber(Observer observer); public void notifySubscribers(String email); }
In this example, the store is the Subject. It contains a list of observers, which are all subscriptions to the news of the store.
import java.util.ArrayList; import java.util.List; public class Store implements Subject { protected List<Observer> observers = new ArrayList<Observer>(); protected String name; protected String news; public Store(String name) { super(); this.name = name; this.news = " - FROM : " + name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEaddress() { return news; } public void sendNews(String news) { System.out.printf("\nName: %s, News : %s\n", name, news); notifySubscribers(news); } @Override public synchronized void addSubscriber(Observer observer) { observers.add(observer); } @Override public synchronized void removeSubscriber(Observer observer) { observers.remove(observer); } @Override public void notifySubscribers(String n) { observers.forEach(observer -> observer.notification(news, n)); } }
People who are subscribed implement the Observer Interface. They register the name and get notifications.
public class Subscriber implements Observer { protected String name; public Subscriber(String name) { super(); this.name = name; } @Override public void notification(String handle, String news) { System.out.printf("%s received news: %s - NEWS: '%s'\n",name, handle, news); } }
The application class declares objects of stores and subscribers, sends notifications, and removes subscribers.
public class EmailSystem { public static void main(String args[]) { Store n1 = new Store("21Store"); Subscriber s1 = new Subscriber("Viki"); Subscriber s2 = new Subscriber("Rachel"); n1.addSubscriber(s1); n1.addSubscriber(s2); n1.sendNews("Summer sales!"); n1.removeSubscriber(s2); n1.sendNews("Only in August"); } }
In Console:
Name: 21Store, News : Summer sales! Viki received news: - FROM : 21Store - NEWS: 'Summer sales!' Rachel received news: - FROM : 21Store - NEWS: 'Summer sales!' Name: 21Store, News : Only for new arrivals Viki received news: - FROM : 21Store - NEWS: 'Only in August'
The Observer Design Pattern is very popular, so try to understand its principle because you might use it.
For more Java Examples, visit Code in Java
Keep coding…