Commit 3ba29da5 authored by Jostein Hjortland Tysse's avatar Jostein Hjortland Tysse
Browse files

Legg til LF for øving 6 og 7

parent d62582e3
package oving6.delegation;
import java.util.HashMap;
import java.util.Map;
public class DistributingLogger implements ILogger {
private Map<String, ILogger> loggers = new HashMap<String, ILogger>();
public DistributingLogger(ILogger errorLogger, ILogger warningLogger, ILogger infoLogger) {
setLogger(ILogger.ERROR, errorLogger);
setLogger(ILogger.WARNING, warningLogger);
setLogger(ILogger.INFO, infoLogger);
}
public void setLogger(String severity, ILogger logger) {
loggers.put(severity, logger);
}
@Override
public void log(String severity, String message, Exception e) {
ILogger logger = loggers.get(severity);
if (logger != null) {
logger.log(severity, message, e);
}
}
}
package oving6.delegation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class FilteringLogger implements ILogger {
private final Collection<String> severities;
private ILogger logger;
public FilteringLogger(ILogger logger, String... severities) {
this.severities = new ArrayList<String>(Arrays.asList(severities));
this.logger = logger;
}
public boolean isLogging(String severity) {
return severities.contains(severity);
}
public void setIsLogging(String severity, boolean value) {
if (!value) {
severities.remove(severity);
} else if (!isLogging(severity)) {
severities.add(severity);
}
}
@Override
public void log(String severity, String message, Exception e) {
if (isLogging(severity)) {
logger.log(severity, message, e);
}
}
}
package oving6.delegation;
public interface ILogger {
public String ERROR = "error", WARNING = "warning", INFO = "info";
public void log(String severity, String message, Exception exception);
}
package oving6.delegation;
import java.io.OutputStream;
import java.io.PrintStream;
public class StreamLogger implements ILogger {
private PrintStream stream;
private String formatString = "%s: %s (%s)";
public StreamLogger(OutputStream stream) {
super();
this.stream = new PrintStream(stream);
}
public void setFormatString(String logFormat) {
this.formatString = logFormat;
}
@Override
public void log(String severity, String message, Exception exception) {
stream.format(formatString, severity, message, exception);
stream.println();
stream.flush();
}
}
package oving6.delegation.office;
import java.util.function.BinaryOperator;
public class Clerk implements Employee {
private Printer printer;
private int calculationCount = 0;
public Clerk(Printer printer) {
this.printer = printer;
}
@Override
public double doCalculations(BinaryOperator<Double> operation, double value1, double value2) {
calculationCount++;
return operation.apply(value1, value2);
}
@Override
public void printDocument(String document) {
printer.printDocument(document, this);
}
@Override
public int getTaskCount() {
return printer.getPrintHistory(this).size() + calculationCount;
}
@Override
public int getResourceCount() {
return 1;
}
}
package oving6.delegation.office;
import java.util.function.BinaryOperator;
public interface Employee {
public double doCalculations(BinaryOperator<Double> operation, double value1, double value2);
public void printDocument(String document);
public int getTaskCount();
public int getResourceCount();
}
package oving6.delegation.office;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.BinaryOperator;
public class Manager implements Employee {
private List<Employee> employees;
private int nextDelegate = 0;
public Manager(Collection<Employee> employees) {
if (employees.isEmpty()) {
throw new IllegalArgumentException("A Manager must have someone to delegate to!");
}
this.employees = new ArrayList<Employee>(employees);
}
private Employee getTaskDelegate() {
return this.employees.get(nextDelegate % employees.size());
}
@Override
public double doCalculations(BinaryOperator<Double> operation, double value1, double value2) {
nextDelegate++;
return getTaskDelegate().doCalculations(operation, value1, value2);
}
@Override
public void printDocument(String document) {
nextDelegate++;
getTaskDelegate().printDocument(document);
}
@Override
public int getTaskCount() {
// Ved hjelp av streams
return employees.stream().mapToInt(employee -> employee.getTaskCount()).sum();
// Alternativt: employees.stream().mapToInt(Employee::getTaskCount).sum()
/*
* Tradisjonell metode
* int task = 0;
* for(Employee e: employees) {
* task += e.getTaskCount();
* }
* return task;
*/
}
@Override
public int getResourceCount() {
int sum = 1;
for (Employee employee : employees) {
sum += employee.getResourceCount();
}
return sum;
}
}
package oving6.delegation.office;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
public class Printer {
private HashMap<Employee, Collection<String>> documentHistories;
public Printer() {
this.documentHistories = new HashMap<Employee, Collection<String>>();
}
public void printDocument(String document, Employee employee) {
if (!documentHistories.containsKey(employee)) {
documentHistories.put(employee, new ArrayList<String>());
}
this.documentHistories.get(employee).add(document);
}
public Collection<String> getPrintHistory(Employee employee) {
if (!documentHistories.containsKey(employee)) {
return Collections.emptyList();
}
return new ArrayList<String>(documentHistories.get(employee));
}
}
package oving6.observable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class HighscoreList {
private int maxSize;
private List<Integer> list = new ArrayList<Integer>();
public int size() {
return list.size();
}
public HighscoreList(int maxSize) {
this.maxSize = maxSize;
}
public void addElement(int pos, int element) {
if (pos < maxSize) {
while (size() >= maxSize) {
list.remove((size() - 1));
}
list.add(pos, element);
fireListChanged(pos);
}
}
protected int getElement(int i) {
return list.get(i);
}
public void addResult(Integer result) {
int pos = 0;
while (pos < size() && result >= (int) list.get(pos)) {
pos++;
}
addElement(pos, result);
}
private Collection<HighscoreListListener> listListeners = new ArrayList<HighscoreListListener>();
public void addHighscoreListListener(HighscoreListListener listListener) {
if (!listListeners.contains(listListener)) {
listListeners.add(listListener);
}
}
public void removeHighscoreListListener(HighscoreListListener listListener) {
listListeners.remove(listListener);
}
protected void fireListChanged(int pos) {
for (HighscoreListListener listListener : listListeners) {
listListener.listChanged(this, pos);
}
}
}
package oving6.observable;
public interface HighscoreListListener {
public void listChanged(HighscoreList list, int pos);
}
package oving6.observable;
import java.util.Scanner;
public class HighscoreListProgram implements HighscoreListListener {
private HighscoreList highscoreList;
public void init() {
this.highscoreList = new HighscoreList(5);
highscoreList.addHighscoreListListener(this);
}
public void run() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int score = scanner.nextInt();
highscoreList.addResult(score);
}
scanner.close();
}
public void listChanged(HighscoreList list, int pos) {
for (int i = 0; i < highscoreList.size(); i++) {
System.out.println(highscoreList.getElement(i) + (pos == i ? (" <=== @ " + pos) : ""));
}
System.out.println();
}
/**
* @param args
*/
public static void main(String[] args) {
HighscoreListProgram program = new HighscoreListProgram();
program.init();
program.run();
}
}
package oving6.observable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SmartStock extends Stock {
// illustrate the use of two different techniques for associating data to a
// listener
// two lists, where items are associated by index/position
private List<StockListener> intervalListeners;
// two doubles for each listener
private List<Double> intervals;
// map from listener to a double array (with two values)
private Map<StockListener, double[]> differenceListeners;
public SmartStock(String ticker, double price) {
super(ticker, price);
intervalListeners = new ArrayList<StockListener>();
intervals = new ArrayList<Double>();
differenceListeners = new HashMap<StockListener, double[]>();
}
public void addStockListener(StockListener listener, double min, double max) {
// double array remembers min and max
intervalListeners.add(listener);
intervals.add(min);
intervals.add(max);
}
public void addStockListener(StockListener listener, double difference) {
// double array remembers difference and last reported price (oldPrice)
differenceListeners.put(listener, new double[] { difference, getPrice() });
}
public void removeStockListener(StockListener listener) {
super.removeStockListener(listener);
intervalListeners.remove(listener);
differenceListeners.remove(listener);
}
// hjelpemetode for aa oppdatere lyttere
protected void firePriceChanged(double oldPrice) {
super.firePriceChanged(oldPrice);
// handle interval listeners
for (int i = 0; i < intervalListeners.size(); i++) {
StockListener listener = intervalListeners.get(i);
// use associated double values
double min = intervals.get(i * 2), max = intervals.get(i * 2 + 1);
double newPrice = getPrice();
if (newPrice < min || newPrice > max) {
listener.stockPriceChanged(this, oldPrice, newPrice);
}
}
// handle difference listeners
for (StockListener listener : differenceListeners.keySet()) {
double[] diffOldPrice = differenceListeners.get(listener);
double newPrice = getPrice();
double difference = diffOldPrice[0], lastReportedPrice = diffOldPrice[1];
if (Math.abs(newPrice - lastReportedPrice) > difference) {
// store back the price to use as oldPrice the next time
diffOldPrice[1] = newPrice;
listener.stockPriceChanged(this, lastReportedPrice, newPrice);
}
}
}
}
package oving6.observable;
import java.util.ArrayList;
import java.util.List;
public class Stock {
private final String ticker;
private double price;
private List<StockListener> listeners;
public Stock(String ticker, double price) {
checkStockPrice(price);
this.ticker = ticker;
this.price = price;
listeners = new ArrayList<StockListener>();
}
public double getPrice() {
return this.price;
}
public String getTicker() {
return this.ticker;
}
private void checkStockPrice(double price) {
if (price <= 0) {
throw new IllegalArgumentException("Stock price must be larger than zero");
}
}
// Endringsmetoden kaller alle lytternes lyttermetode
public void setPrice(double newPrice) {
checkStockPrice(newPrice);
double oldPrice = this.price;
this.price = newPrice;
if (this.price != oldPrice) {
firePriceChanged(oldPrice);
}
}
public void addStockListener(StockListener listener) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
public void removeStockListener(StockListener listener) {
listeners.remove(listener);
}
// helper for notifying listeners
// protected, so it may be called by subclasses
protected void firePriceChanged(double oldPrice) {
for (StockListener listener : listeners) {
listener.stockPriceChanged(this, oldPrice, this.price);
}
}
}
package oving6.observable;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class StockIndex implements StockListener {
private String name;
private List<Stock> stocks;
private double index;
public StockIndex(String name, Stock... stocks) {
this.name = name;
this.stocks = new ArrayList<Stock>(Arrays.asList(stocks));
this.index = 0;
for (Stock s : stocks) {
s.addStockListener(this);
this.index += s.getPrice();
}
}
public String getName() {
return this.name;
}
public double getIndex() {
return this.index;
}
@Override
public void stockPriceChanged(Stock stock, double oldPrice, double newPrice) {
this.index += newPrice - oldPrice;
}
public void addStock(Stock stock) {
if (!this.stocks.contains(stock)) {
this.stocks.add(stock);
stock.addStockListener(this);
this.index += stock.getPrice();
}
}
public void removeStock(Stock stock) {
if (this.stocks.contains(stock)) {
stock.removeStockListener(this);
this.stocks.remove(stock);
this.index -= stock.getPrice();
}
}
}
package oving6.observable;
public interface StockListener {
public void stockPriceChanged(Stock stock, double oldPrice, double newPrice);
}
package oving7;
public abstract class AbstractAccount {
protected double balance;
public AbstractAccount() {
balance = 0;
}
public void deposit(double amount) {
if (amount >= 0) {
balance += amount;
} else {
throw new IllegalArgumentException("Amount must be positive");
}
}
public void withdraw(double amount) {
if (amount >= 0) {
internalWithdraw(amount);
} else {
throw new IllegalArgumentException("Amount cannot be negative");
}
}
protected abstract void internalWithdraw(double amount);
public double getBalance() {
return balance;
}
}
package oving7;
public interface Account {
public void deposit(double amount);
public void withdraw(double amount);
public double getBalance();