import java.awt.Point; import java.util.ArrayList; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Model { private ArrayList points; private ArrayList listeners; /** * Constructor */ public Model() { points = new ArrayList(); listeners = new ArrayList(); if (new java.io.File("points.bin").exists()) { // load points from file try { FileInputStream fi = new FileInputStream("points.bin"); ObjectInputStream in = new ObjectInputStream(fi); points = (ArrayList) in.readObject(); in.close(); fi.close(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } catch (ClassNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } } } public void addListener(ModelListener l) { listeners.add(l); } public ArrayList getPoints() { return points; } public void addPoint(Point p) { points.add(p); notifyListeners(); } public void clearAllPoints() { points.clear(); notifyListeners(); } public void deleteLastPoint() { if (points.size() > 0) { points.remove(points.size() - 1); notifyListeners(); } } private void notifyListeners() { for (ModelListener l : listeners) { l.update(); } } public int numberOfPoints() { return points.size(); } public void saveData() { try { // save points to file FileOutputStream fo = new FileOutputStream("points.bin"); ObjectOutputStream out = new ObjectOutputStream(fo); out.writeObject(points); out.close(); fo.close(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void testModel() { Model m = new Model(); m.addListener(new ModelListener() { @Override public void update() { System.out.println(true + " (listener)"); } }); System.out.println(m.getPoints() == m.points); Point p1 = new Point(1, 2); Point p2 = new Point(3, 4); m.addPoint(p1); m.addPoint(p2); System.out.println(m.numberOfPoints() == 2); System.out.println(m.points.get(0) == p1); System.out.println(m.points.get(1) == p2); m.deleteLastPoint(); System.out.println(m.numberOfPoints() == 1); System.out.println(m.points.get(0) == p1); m.clearAllPoints(); System.out.println(m.numberOfPoints() == 0); m.notifyListeners(); } }