На случай, если кому-то интересно, я собрал это через несколько минут после публикации моего вопроса:
import org.apache.commons.lang.StringUtils;
public class Counter {
private int value;
private int padding;
public Counter() {
this(0, 4);
}
public Counter(int value) {
this(value, 4);
}
public Counter(int value, int padding) {
this.value = value;
this.padding = padding;
}
public Counter incr() {
this.value++;
return this;
}
public Counter decr() {
this.value--;
return this;
}
@Override
public String toString() {
return StringUtils.leftPad(Integer.toString(this.value),
this.padding, "0");
// OR without StringUtils:
// return String.format("%0"+this.padding+"d", this.value);
}
}
Единственная проблема с этим заключается в том, что я должен вызвать toString()
, чтобы получить из него строку, или добавить ее к строке, такой как ""+counter
:
@Test
public void testCounter() {
Counter counter = new Counter();
assertThat("0000", is(counter.toString()));
counter.incr();
assertThat("0001",is(""+counter));
assertThat("0002",is(counter.incr().toString()));
assertThat("0001",is(""+counter.decr()));
assertThat("001",is(not(counter.toString())));
}