Question: In the Observer Design Pattern, the subject class needs to maintain a list of observers that should be notified of any changes in its state.

In the Observer Design Pattern, the subject class needs to maintain a list of observers that should be notified of any changes in its state. In a Java implementation, this is often facilitated by the addObserver(Observer o) method. What is the purpose of the addObserver(Observer o) method in the subject class?
Example code:
import java.util.ArrayList;
import java.util.List;
// Abstract Subject class that manages observers and notifications
abstract class Subject {
private List observers = new ArrayList<>();
public void addObserver(Observer observer){
observers.add(observer);
}
public void removeObserver(Observer observer){
observers.remove(observer);
}
public void notifyObservers(){
for (Observer observer : observers){
observer.update();
}
}
}
// Concrete implementation of Subject
class ConcreteSubject extends Subject {
private String state;
public void setState(String state){
this.state = state;
notifyObservers();
}
public String getState(){
return this.state;
}
}
// Observer interface
interface Observer {
void update();
}
// Concrete implementation of Observer
class ConcreteObserver implements Observer {
public void update(){
System.out.println("Observer notified of change!");
}
}
// Demo class to show the Observer Pattern in action
public class ObserverPatternDemo {
public static void main(String[] args){
ConcreteSubject subject = new ConcreteSubject();
Observer observer1= new ConcreteObserver();
subject.addObserver(observer1);
subject.setState("New State"); // This should trigger observer notification
}
}
It updates the state of the subject based on the observer's state.
It sends an update notification to all registered observers.
It registers a new observer to receive updates from the subject.
It removes an observer from the subject's list of observers.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!