1 // Datum.java
2 package objectstreams;
3 import java.util.Calendar;
4 import java.io.Serializable;
5
6 /** 7 * Datum ist ein Bauplan für Datumswerte. 8 * Verwendung von Serializable ist ein Sicherheitsrisiko! 9 * @author H.Drachenfels 10 * @version 17.1.2020 11 */
12 public final class Datum implements Serializable {
13 private static final String[] MONATE = {
14 "Januar",
15 "Februar",
16 "Maerz",
17 "April",
18 "Mai",
19 "Juni",
20 "Juli",
21 "August",
22 "September",
23 "Oktober",
24 "November",
25 "Dezember"
26 };
27
28 private final int tag;
29 private final String monat;
30 private final int jahr;
31
32 private Datum(/* final Datum this, */ int tag, int monat, int jahr) {
33 this.tag = tag;
34 this.monat = MONATE[monat - 1];
35 this.jahr = jahr;
36 }
37
38 /** 39 * Fabrikmethode, die ein value object mit dem angegebenen Datum liefert. 40 * @param tag ist der Tag im Monat 41 * @param monat ist der Monat im Jahr 42 * @param jahr ist das Jahr 43 * @return Referenz auf das value object 44 */
45 public static Datum valueOf(int tag, int monat, int jahr) {
46 // Datum pruefen (stark vereinfacht)
47 if (tag < 1 || tag > 31 || monat < 1 || monat > 12) {
48 throw new IllegalArgumentException("ungueltiges Datum");
49 }
50
51 // value object erzeugen
52 return new Datum(tag, monat, jahr);
53 }
54
55 /** 56 * Fabrikmethode, die ein value object mit dem aktuellen Datum liefert. 57 * @return Referenz auf das value object 58 */
59 public static Datum heute() {
60 // Systemkalender ablesen
61 Calendar c = Calendar.getInstance();
62
63 // value object erzeugen
64 return new Datum(c.get(Calendar.DAY_OF_MONTH),
65 c.get(Calendar.MONTH) + 1,
66 c.get(Calendar.YEAR));
67 }
68
69 @Override
70 public String toString(/* final Datum this */) {
71 return String.format("%d. %s %d", this.tag, this.monat, this.jahr);
72 }
73
74 @Override
75 public boolean equals(/* final Datum this, */ Object o) {
76 if (o instanceof Datum) {
77 Datum that = (Datum) o;
78 return this.tag == that.tag
79 && this.monat.equals(that.monat)
80 && this.jahr == that.jahr;
81 }
82
83 return false;
84 }
85
86 @Override
87 public int hashCode(/* final Datum this */) {
88 return ((this.jahr << 5) + this.tag) ^ this.monat.hashCode();
89 }
90 }
91