added observer example

This commit is contained in:
Louis Heredero 2024-11-11 11:16:34 +01:00
parent 6eee9df1fe
commit ca9d0ec062
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
5 changed files with 76 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package learn.simple_observer;
public class ConcreteObserver implements Observer {
private ConcreteSubject subject;
public ConcreteObserver(ConcreteSubject subject) {
this.subject = subject;
subject.registerObserver(this);
}
@Override
public void update() {
System.out.println("Observer was notified: subject has new state: " + subject.getState());
}
}

View File

@ -0,0 +1,37 @@
package learn.simple_observer;
import java.util.ArrayList;
import java.util.List;
public class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
int state;
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notifyObservers() {
for (Observer o : observers) {
o.update();
}
}
public void setState(int state) {
this.state = state;
if (state > 50) {
notifyObservers();
}
}
public int getState() {
return state;
}
}

View File

@ -0,0 +1,12 @@
package learn.simple_observer;
public class Main {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
Observer observer = new ConcreteObserver(subject);
subject.setState(40);
subject.setState(100);
Observer observer2 = new ConcreteObserver(subject);
subject.setState(200);
}
}

View File

@ -0,0 +1,5 @@
package learn.simple_observer;
public interface Observer {
void update();
}

View File

@ -0,0 +1,7 @@
package learn.simple_observer;
public interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}