samples/openfixed/src/org/apidesign/openfixed/Calculator.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 30 Oct 2014 21:30:10 +0100
changeset 409 40cabcdcd2be
parent 375 3abae898011d
permissions -rw-r--r--
Updating to NBMs from NetBeans 8.0.1 as some of them are required to run on JDK8
     1 package org.apidesign.openfixed;
     2 
     3 /** Sample bean using the {@link ModificationListener}
     4  * to <b>add</b> numbers.
     5  *
     6  * @author Jaroslav Tulach <jtulach@netbeans.org>
     7  */
     8 // BEGIN: openfixed.bean
     9 public final class Calculator {
    10     private final EventSupport listeners;
    11     private int sum;
    12 
    13     private Calculator(EventSupport listeners) {
    14         this.listeners = listeners;
    15     }
    16 
    17     /** An abstraction over various types of event delivery
    18      * to listeners. Comes with four different implementations.
    19      * A trivial one, asynchronous one, one with support for
    20      * pending events and one for a batch events delivery.
    21      */
    22     interface EventSupport {
    23         public void fireModificationEvent(ModificationEvent ev);
    24         public void add(ModificationListener l);
    25         public void remove(ModificationListener l);
    26     }
    27     
    28     public static Calculator create() {
    29         return new Calculator(new TrivialEventSupport());
    30     }
    31 
    32     public static Calculator createAsynch() {
    33         return new Calculator(new AsyncEventSupport());
    34     }
    35 
    36     /** @since 2.0 */
    37     public static Calculator createPending() {
    38         return new Calculator(new PendingEventSupport());
    39     }
    40 
    41     /** @since 3.0 */
    42     public static Calculator createBatch() {
    43         return new Calculator(new PostEventSupport());
    44     }
    45 
    46     public synchronized void add(int add) {
    47         sum += add;
    48         listeners.fireModificationEvent(new ModificationEvent(this, add));
    49     }
    50     
    51     public synchronized int getSum() {
    52         return sum;
    53     }
    54     
    55     public void addModificationListener(ModificationListener l) {
    56         listeners.add(l);
    57     }
    58     public void removeModificationListener(ModificationListener l) {
    59         listeners.remove(l);
    60     }
    61 }
    62 // END: openfixed.bean