Commit 7b4717b1 authored by ElaFHNW's avatar ElaFHNW
Browse files

observer pattern

parent bf6402c9
package designPattern.Observer;
public interface Channel {
public void update(Object o);
}
package designPattern.Observer;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
class EventSource {
public interface Observer {
void update(String event);
}
private final List<Observer> observers = new ArrayList<>();
private void notifyObservers(String event) {
observers.forEach(observer -> observer.update(event));
}
public void addObserver(Observer observer) {
observers.add(observer);
}
public void scanSystemIn() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
notifyObservers(line);
}
scanner.close();
}
}
\ No newline at end of file
package designPattern.Observer;
import java.util.ArrayList;
import java.util.List;
// publisher object
public class NewsAgency {
private String news;
private List<Channel> channels = new ArrayList<>();
public void addObserver(Channel channel) {
this.channels.add(channel);
}
public void removeObserver(Channel channel) {
this.channels.remove(channel);
}
public void setNews(String news) {
this.news = news;
for (Channel channel : this.channels) {
channel.update(this.news);
}
}
}
package designPattern.Observer;
public class NewsChannel implements Channel {
private String news;
public void setNews(String news) {
this.news = news;
}
public String getNews() {
return news;
}
@Override
public void update(Object news) {
this.setNews((String) news);
}
}
package designPattern.Observer;
// also see https://www.youtube.com/watch?v=_BpmfnqjgzQ, Okhravi
public class ObserverDemo {
public static void main(String[] args) {
System.out.println("Enter Text: ");
EventSource eventSource = new EventSource();
eventSource.addObserver(event -> {
System.out.println("Received response: " + event);
});
eventSource.scanSystemIn();
}
}
\ No newline at end of file
package designPattern.Observer;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestAgencyChannel {
public static void main(String [] args) {
NewsAgency observable = new NewsAgency();
NewsChannel observer = new NewsChannel();
observable.addObserver(observer);
observable.setNews("news");
assertEquals(observer.getNews(), "news");
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment