Drools高级技巧:Accumulate函数
?
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Created on Jun 21, 2007
*/
package org.drools.base.accumulators;
<o:p>?</o:p>
<o:p>?</o:p>
/**
* An implementation of an accumulator capable of calculating average values
*
?* @author etirelli
*
*/
public class AverageAccumulateFunction implements AccumulateFunction {
<o:p>?</o:p>
??? protected static class AverageData {
??????? public int??? count = 0;
??????? public double total = 0;
??? }
<o:p>?</o:p>
??? /* (non-Javadoc)
???? * @see org.drools.base.accumulators.AccumulateFunction#createContext()
???? */
??? public Object createContext() {
??????? return new AverageData();
??? }
<o:p>?</o:p>
??? /* (non-Javadoc)
???? * @see org.drools.base.accumulators.AccumulateFunction#init(java.lang.Object)
???? */
??? public void init(Object context) throws Exception {
??????? AverageData data = (AverageData) context;
??????? data.count = 0;
??????? data.total = 0;
??? }
<o:p>?</o:p>
??? /* (non-Javadoc)
???? * @see org.drools.base.accumulators.AccumulateFunction#accumulate(java.lang.Object, java.lang.Object)
???? */
??? public void accumulate(Object context,
?????????????????????????? Object value) {
??????? AverageData data = (AverageData) context;
??????? data.count++;
??????? data.total += ((Number) value).doubleValue();
??? }
<o:p>?</o:p>
??? /* (non-Javadoc)
???? * @see org.drools.base.accumulators.AccumulateFunction#reverse(java.lang.Object, java.lang.Object)
???? */
??? public void reverse(Object context,
??????????????????????? Object value) throws Exception {
??????? AverageData data = (AverageData) context;
??????? data.count--;
??????? data.total -= ((Number) value).doubleValue();
??? }
<o:p>?</o:p>
??? /* (non-Javadoc)
???? * @see org.drools.base.accumulators.AccumulateFunction#getResult(java.lang.Object)
???? */
??? public Object getResult(Object context) throws Exception {
??????? AverageData data = (AverageData) context;
??????? return new Double( data.count == 0 ? 0 : data.total / data.count );
??? }
<o:p>?</o:p>
??? /* (non-Javadoc)
???? * @see org.drools.base.accumulators.AccumulateFunction#supportsReverse()
???? */
??? public boolean supportsReverse() {
??????? return true;
??? }
<o:p>?</o:p>
}
<o:p>?</o:p>