Commit ee864636 authored by Børge Haugset's avatar Børge Haugset
Browse files

lala

parent 7e11ae41
package uke12.listener.stocks_forelesning;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class FileObserver implements IObserver{
public FileObserver(Observable observable) {
observable.addObserver(this);
}
@Override
public void update(Observable observable, String name) {
try (PrintWriter printWriter = new PrintWriter(new BufferedWriter(
new FileWriter("Fil.txt", true)))) {
} catch (Exception e) {
}
}
}
package uke12.listener.stocks_forelesning;
public interface IObserver {
public void update(Observable observable, String name);
}
package uke12.listener.stocks_forelesning;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class Observable {
Map<String, Double> stocks = new HashMap<>();
Collection<IObserver> observers = new ArrayList<>();;
public void updateStock(String name, double value) {
stocks.put(name, stocks.getOrDefault(name, 0.0) + value);
System.out.println(name+" oppdater");
notifyObservers(name);
}
private void notifyObservers(String name) {
for (IObserver iobserver : observers) {
iobserver.update(this, name);
}
}
public void addObserver(IObserver observer) {
this.observers.add(observer);
}
public void removeObserver(IObserver observer) {
this.observers.remove(observer);
}
public double getStockValue(String name) {
return stocks.get(name);
}
}
package uke12.listener.stocks_forelesning;
public class Observer implements IObserver{
public Observer(Observable observable) {
observable.addObserver(this);
}
public void update(Observable observable, String name) {
System.out.println("Ny endring i "+name+": "+
observable.getStockValue(name));
}
}
package uke12.listener.stocks_forelesning;
public class RunMe {
public static void main(String[] args) {
Observable observable = new Observable();
Observer observer = new Observer(observable);
observable.updateStock("Equinoor", 500);
observable.updateStock("Equinoor", 50);
observable.updateStock("Frosta skotthyll&poff", 50);
}
}
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