samples/codeinjection/src/org/apidesign/codeinjection/CountDownImplV2.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sun, 06 Oct 2013 22:05:14 +0200
changeset 407 e1439046d96e
parent 304 adb083bd81c5
permissions -rw-r--r--
Looks like scala change URLs of its releases
     1 /*
     2  * To change this template, choose Tools | Templates
     3  * and open the template in the editor.
     4  */
     5 
     6 package org.apidesign.codeinjection;
     7 
     8 import java.util.Iterator;
     9 import java.util.ServiceLoader;
    10 import org.apidesign.codeinjection.spi.CountDownExtender;
    11 
    12 /** Second version to {@link CountDownImplV1} - imagine someone wants to
    13  * reimplement {@link #down()} method to decrement by two not just by one.
    14  * You do not like that idea at all, but you do not want to prevent such
    15  * behaviour. You just do not want to maintain such bloody code. What can
    16  * you do? You need to allow <b>code injection</b> via the
    17  * {@link CountDownExtender} class!
    18  *
    19  * @author Jaroslav Tulach <jtulach@netbeans.org>
    20  */
    21 final class CountDownImplV2 extends CountDown {
    22     private int cnt;
    23 
    24     CountDownImplV2(int initial) {
    25         this.cnt = initial;
    26     }
    27 
    28 // BEGIN: codeinjection.v2
    29     public void down() {
    30         Iterator<CountDownExtender> it =
    31             ServiceLoader.load(CountDownExtender.class).iterator();
    32         if (it.hasNext()) {
    33             // injected behaviour
    34             cnt = it.next().decrement(cnt);
    35         } else {
    36             // common behaviour of 1.0 version
    37             cnt--;
    38         }
    39     }
    40 
    41     public boolean isDown() {
    42         return cnt <= 0;
    43     }
    44 // END: codeinjection.v2
    45 }