This commit is contained in:
2022-05-22 23:34:42 +08:00
parent d0416b02bd
commit a9f7967976
30 changed files with 904 additions and 0 deletions

View File

@@ -0,0 +1,106 @@
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<Point> points;
private ArrayList<ModelListener> listeners;
public Model() {
points = new ArrayList<Point>();
listeners = new ArrayList<ModelListener>();
if (new java.io.File("points.bin").exists()) {
try {
FileInputStream fi = new FileInputStream("points.bin");
ObjectInputStream in = new ObjectInputStream(fi);
points = (ArrayList<Point>) 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<Point> 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 {
FileOutputStream f = new FileOutputStream("points.bin");
ObjectOutputStream out = new ObjectOutputStream(f);
out.writeObject(points);
out.close();
f.close();
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(254);
}
}
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();
}
}