1 // Datum.java
2 import java.util.Calendar;
3
4 /** 5 * Datum ist ein Bauplan für Datumswerte. 6 * Beispielprogramm zur Programmiertechnik 1, Teil 4. 7 * @author H.Drachenfels 8 * @version 19.12.2016 9 */
10 public final class Datum {
11 /** Instanzvariable speichert den Tag im Monat. */
12 public final int tag;
13 /** Instanzvariable speichert den Monat im Jahr. */
14 public final int monat;
15 /** Instanzvariable speichert das Jahr. */
16 public final int jahr;
17
18 private Datum(/* final Datum this, */ int tag, int monat, int jahr) {
19 this.tag = tag;
20 this.monat = monat;
21 this.jahr = jahr;
22 }
23
24 /** 25 * Fabrikmethode, die ein value object mit dem angegebenen Datum liefert. 26 * @param tag ist der Tag im Monat 27 * @param monat ist der Monat im Jahr 28 * @param jahr ist das Jahr 29 * @return Referenz auf das value object 30 */
31 public static Datum valueOf(int tag, int monat, int jahr) {
32 // Datum pruefen (stark vereinfacht)
33 if (tag < 1 || tag > 31 || monat < 1 || monat > 12) {
34 throw new IllegalArgumentException("ungueltiges Datum");
35 }
36
37 // value object erzeugen
38 return new Datum(tag, monat, jahr);
39 }
40
41 /** 42 * Fabrikmethode, die ein value object mit dem aktuellen Datum liefert. 43 * @return Referenz auf das value object 44 */
45 public static Datum heute() {
46 // Systemkalender ablesen
47 Calendar c = Calendar.getInstance();
48
49 // value object erzeugen
50 return new Datum(c.get(Calendar.DAY_OF_MONTH),
51 c.get(Calendar.MONTH) + 1,
52 c.get(Calendar.YEAR));
53 }
54
55 @Override
56 public String toString(/* final Datum this */) {
57 return String.format("%04d-%02d-%02d", this.jahr, this.monat, this.tag);
58 }
59
60 @Override
61 public boolean equals(/* final Datum this, */ Object o) {
62 if (o instanceof Datum) {
63 Datum that = (Datum) o;
64 return this.tag == that.tag
65 && this.monat == that.monat
66 && this.jahr == that.jahr;
67 }
68
69 return false;
70 }
71
72 @Override
73 public int hashCode(/* final Datum this */) {
74 return (this.jahr << 9) + (this.monat << 5) + this.tag;
75 }
76 }
77