Software Design Patterns and Principles - Part 12 (Observer Design Pattern)
Saiful Islam Rasel
Senior Engineer, SDE @ bKash | Ex: AsthaIT | Sports Programmer | Problem Solver | FinTech | Microservice | Java | Spring-boot | C# | .NET | PostgreSQL | DynamoDB | JavaScript | TypeScript | React.js | Next.js | Angular
**** Previous Parts ****
Part 1: Introduction
Story:
Roni is owner of a confectionery shop near a girls school. There he sells chocolate, sweet, ice-cream and other thing. Rina is a student of class 10 of this girls school who often visits Roni's shop for buying ice-cream and chocolate. Anik is a neighbor of Roni who likes Rina a lot. As a result, Anik frequently visit Roni's shop and continuously asks about Rina, is he come, when come etc. Here not only Anik, some other little brothers often disturb Roni. So after some days situation got very serious and Roni tells, Anik and others to give him theirs phone number so that he can inform them when Rina and others visits his shop.
Observer Design Pattern:
Definition:
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re?observing.
As the definition stat, Observer design pattern gives a subscription mechanism where one or more objects can subscribe to a publisher object and when any change happens then publisher can notify the subscriber object about the changes. Also subscriber can unsubscribe any time if it wanted. So subscriber objects observe the publisher object and react based on it.
Problem:
In the above story, Roni got disturb and situation is not so nice for Anik and others continuous knocking. So he need a solution by which anyone not knocking him, rather he will inform others. How this can be achieved?
The observer design pattern is a widely used pattern in software engineering for implementing distributed event handling systems, in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them of any state changes, usually by calling one of their methods. Here are some scenarios where the observer design pattern can be applied:
领英推荐
Overall, the observer pattern provides a flexible and efficient way to handle communication and coordination between different components of a system, making it a valuable tool in various software development scenarios.
Solution:
In the above story, Roni asked for the phone numbers of Anik and others. So Anik and other give him their phone numbers and tell him to call when their likes person visit his shop. So Roni here is subject/publisher who will inform about the event (here event is Rina and other girls). And Anik and others boy are subscriber whom subscribe Roni by giving their phone number. So as a result, observer pattern solves their problem.
We can also use or implement observer pattern as a solution of the problems stated earlier sections as well.
UML Diagram:
Here in UML diagram we can see that, There can be multiple ConcreteObserver who is implementing the common Observer interface. Then a Subject class which is mainly the publisher holds the observer list and give a attach and detach mechanism for observer in the subscription list. So when any event happens on Subject it immediately publish or notify the Observer objects.
When to use:
Implementation:
import java.util.ArrayList;
import java.util.List;
// Subject interface
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
// Concrete Subject class
class WeatherStation implements Subject {
private int temperature;
private List<Observer> observers;
public WeatherStation() {
observers = new ArrayList<>();
}
public void setTemperature(int temperature) {
this.temperature = temperature;
notifyObservers();
}
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(temperature);
}
}
}
// Observer interface
interface Observer {
void update(int temperature);
}
// Concrete Observer classes
class PhoneDisplay implements Observer {
@Override
public void update(int temperature) {
System.out.println("Phone Display: Current temperature is " + temperature + " degrees Celsius.");
}
}
class LaptopDisplay implements Observer {
@Override
public void update(int temperature) {
System.out.println("Laptop Display: Current temperature is " + temperature + " degrees Celsius.");
}
}
public class ObserverPatternExample {
public static void main(String[] args) {
WeatherStation weatherStation = new WeatherStation();
PhoneDisplay phoneDisplay = new PhoneDisplay();
LaptopDisplay laptopDisplay = new LaptopDisplay();
weatherStation.registerObserver(phoneDisplay);
weatherStation.registerObserver(laptopDisplay);
// Simulate temperature change
weatherStation.setTemperature(25);
// Unregister laptop display
weatherStation.removeObserver(laptopDisplay);
// Simulate temperature change again
weatherStation.setTemperature(30);
}
}
Another C# implementation of Observer design pattern.
Achieved Design Principles:
The Observer design pattern helps achieve several Object-Oriented Programming (OOP) and software design principles, including:
By adhering to these principles, the Observer pattern promotes good software design practices such as modularity, extensibility, and maintainability, making it a valuable tool for building robust and flexible software systems.
Happy Learning !!!
Happy Coding !!!
Happy Programming !!!
Senior Engineer, SDE @ bKash | Ex: AsthaIT | Sports Programmer | Problem Solver | FinTech | Microservice | Java | Spring-boot | C# | .NET | PostgreSQL | DynamoDB | JavaScript | TypeScript | React.js | Next.js | Angular
6 个月Previous Parts: Part 1: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-1-saiful-islam-rasel-eqfec/ Part 2: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-2-list-most-rasel-kepmc/ Part 3: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-3-factory-method-rasel-ir4tc/ Part 4: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-4-builder-pattern-rasel-41cmc/ Part 5: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-5-adapter-pattern-rasel-nfjrc/ Part 6: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-6-decorator-rasel-ijxwc/ Part 7: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-7-composite-rasel-tuzfc/ Part 8: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-8-fa%2525C3%2525A7ade-pattern-rasel-6bucc/ Part 9: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-9-proxy-pattern-rasel-ajmgc/ Part 10: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-10-command-rasel-qyaic/ Part 11: https://www.dhirubhai.net/pulse/software-design-patterns-principles-part-11-mediator-rasel-iuszc/