This commit is contained in:
0nlineSam 2024-12-07 13:10:08 +01:00
parent fcc25f0c21
commit 221d9cb5d8
3 changed files with 48 additions and 8 deletions

View File

@ -4,10 +4,19 @@ import model.Article;
import model.Image;
import model.NewsCollection;
public class Client {
import java.util.Observable;
import java.util.Observer;
public class Client implements Observer {
public static void main(String[] args) {
Client client = new Client();
client.run();
}
public void run() {
NewsCollection masterCollection = new NewsCollection("Daily news");
masterCollection.addObserver(this);
Article changedArticle = new Article("Harder, Better, Faster, Stronger. Doping controls loosened","ups");
@ -23,9 +32,18 @@ public class Client {
System.out.print(masterCollection.getOverviewInformation());
System.out.println("\n===Contents===\n");
System.out.print(masterCollection.getDetailedInformation());
masterCollection.addObserver(this);
System.out.println("\n===After change===\n");
changedArticle.setTitle("Harder, Better, Faster, Stronger? Doping controls loosened");
masterCollection.addItem(new Image("A tasty cat", 640, 480, "alf"));
}
@Override
public void update(Observable o, Object arg) {
System.out.println("### UPDATE ###");
System.out.println(arg);
}
}

View File

@ -1,16 +1,29 @@
package model;
import java.util.LinkedList;
import java.util.List;
import java.util.*;
public class NewsCollection extends NewsItem {
private Set<Observer> observers = new HashSet<>();
private List<NewsItem> newsItems = new LinkedList<NewsItem>();
public NewsCollection(String topic) {
this.title = topic;
}
@Override
public synchronized void addObserver(Observer o) {
super.addObserver(o);
observers.add(o);
newsItems.forEach(i -> i.addObserver(o));
}
@Override
public synchronized void deleteObserver(Observer o) {
super.deleteObserver(o);
observers.remove(o);
newsItems.forEach(i -> i.deleteObserver(o));
}
/**
* Get the list of items stored in this collection.
* @return items stored in this collection
@ -25,7 +38,11 @@ public class NewsCollection extends NewsItem {
* @return this collection (enables method chaining)
*/
public NewsCollection addItem(NewsItem item) {
String updateNotification = getTitle() + "\n+ " + item.getTitle() + "\n";
newsItems.add(item);
setChanged();
notifyObservers(updateNotification);
observers.forEach(item::addObserver);
return this;
}
@ -54,5 +71,5 @@ public class NewsCollection extends NewsItem {
builder.append("\n");
}
return builder.toString();
}
}
}

View File

@ -1,6 +1,8 @@
package model;
public abstract class NewsItem {
import java.util.Observable;
public abstract class NewsItem extends Observable {
protected String title;
@ -17,7 +19,10 @@ public abstract class NewsItem {
}
public void setTitle(String newTitle) {
String updateNotification = "- " + title + "\n+ " + newTitle + "\n";
title = newTitle;
setChanged();
notifyObservers(updateNotification);
}
/**