1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/samples/codeinjection/src/org/apidesign/codeinjection/CountDownImplV2.java Sat Jan 10 21:29:22 2009 +0100
1.3 @@ -0,0 +1,44 @@
1.4 +/*
1.5 + * To change this template, choose Tools | Templates
1.6 + * and open the template in the editor.
1.7 + */
1.8 +
1.9 +package org.apidesign.codeinjection;
1.10 +
1.11 +import java.util.Iterator;
1.12 +import java.util.ServiceLoader;
1.13 +import org.apidesign.codeinjection.spi.CountDownExtender;
1.14 +
1.15 +/** Second version to {@link CountDownImplV1} - imagine someone wants to
1.16 + * reimplement {@link #down()} method to decrement by two not just by one.
1.17 + * You do not like that idea at all, but you do not want to prevent such
1.18 + * behaviour. You just do not want to maintain such bloody code. What can
1.19 + * you do? You need to allow <b>code injection</b> via the
1.20 + * {@link CountDownExtender} class!
1.21 + *
1.22 + * @author Jaroslav Tulach <jtulach@netbeans.org>
1.23 + */
1.24 +final class CountDownImplV2 extends CountDown {
1.25 + private int cnt;
1.26 +
1.27 + CountDownImplV2(int initial) {
1.28 + this.cnt = initial;
1.29 + }
1.30 +
1.31 +// BEGIN: codeinjection.v2
1.32 + public void down() {
1.33 + Iterator<CountDownExtender> it = ServiceLoader.load(CountDownExtender.class).iterator();
1.34 + if (it.hasNext()) {
1.35 + // injected behaviour
1.36 + cnt = it.next().decrement(cnt);
1.37 + } else {
1.38 + // common behaviour of 1.0 version
1.39 + cnt--;
1.40 + }
1.41 + }
1.42 +
1.43 + public boolean isDown() {
1.44 + return cnt <= 0;
1.45 + }
1.46 +// END: codeinjection.v2
1.47 +}