public class Counter { private int counter; private Counter(int i) { this.safeSetCounter(i); } public void click() { this.safeSetCounter(this.counter + 1); } private void safeSetCounter(int i) { this.counter = i % 10000; } public void reset() { this.counter = 0; } public int value() { return this.counter; } public static Counter zero() { return new Counter(0); } /** * Returns a new Counter with de defined value included between 0 and 9999. Throws an IllegalArgumentException * if the value is out of the range * * @param value the initial value between 0 and 9999 * @return a counter with the given value set * @throws IllegalArgumentExcpetion if value is not included in the specific range */ public static Counter withValue(int value) { if (value < 0 || value > 9999) { /* Nous préférons retourner une exception si l'utilisateur fait une bêtise */ throw new IllegalArgumentException("Value must be between 0 and 9999"); } return new Counter(value); } private String toFourDigits(int i) { final String tooMuchDigits = ("0000" + this.counter); return tooMuchDigits.substring( tooMuchDigits.length()-4, tooMuchDigits.length() ); } public String toString() { return "Counter(" + toFourDigits(this.counter) + ")"; } public static void main(String[] args) { Counter counter = Counter.withValue(10); System.out.println( counter ); } }