表达式合成
表达式合成是得到同样结果的一种稍有不同的技术。考虑计算特定 SETLItem 的净价问题,要考虑当前折扣和销售税率。清单 3 列出了这个问题基于仿函数的解决方式。
清单 3. 表达式合成方法
package com.infosys.setl.fp;
import org.apache.commons.functor.BinaryFunction;
import org.apache.commons.functor.UnaryFunction;
import org.apache.commons.functor.adapter.LeftBoundFunction;
public class Multiply implements BinaryFunction
{
public Object evaluate(Object left, Object right)
{
return new Double(((Double)left).doubleValue() * ((Double)right).doubleValue());
}
}
package com.infosys.setl.fp;
import org.apache.commons.functor.*;
import org.apache.commons.functor.core.composite.*;
import org.apache.commons.functor.adapter.*;
import org.apache.commons.functor.UnaryFunction;
public class TestB
{
public static void main(String[] args)
{
try
{
double discountRate = 0.1;
double taxRate=0.33;
SETLItem item = new SETLItem();
item.setPrice(100);
UnaryFunction calcDiscountedPrice =
new RightBoundFunction(new Multiply(), new Double(1-discountRate));
UnaryFunction calcTax =
new RightBoundFunction(new Multiply(), new Double(1+taxRate));