首页 > 解决方案 > 按照 Venkat Subramaniam 的书使用 lambda 表达式来玩策略设计模式?

问题描述

我正在关注Subramaniam 教授的。书中教授试图解释Delegating Using Lambda Expressions.

我们使用 lambda 表达式和策略模式将关注点与方法分开。我们还可以使用它们将关注点与类分开。从重用的角度来看,委托是比继承更好的设计工具。通过委托,我们可以更轻松地改变我们所依赖的实现,并且我们可以更动态地插入不同的行为。这可以帮助改变类的行为,使其独立于它们所依赖的部分的行为,并使设计更加灵活,而不会强制使用更深的类层次结构

这是一个具有静态方法的特定类,它执行所需的信息计算/获取。

 public class YahooFinance {
        public static BigDecimal getPrice(final String ticker) {
            try {
                final URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + ticker);
                final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                final String data = reader.lines().skip(1).findFirst().get();
                final String[] dataItems = data.split(",");
                return new BigDecimal(dataItems[dataItems.length - 1]);
            } catch(Exception ex) {
                throw new RuntimeException(ex);
            }
        }
  }

Creating a Delegate: 我们可以将其委托给 lambda 表达式和方法引用,而不是将部分责任委托给另一个类。这将进一步减少类扩散。

这是客户端代码(即Delegate):

public class CalculateNAV {
    

    private Function<String, BigDecimal> priceFinder;
    
      public CalculateNAV(final Function<String, BigDecimal> aPriceFinder) {
          priceFinder = aPriceFinder;
      }

      public BigDecimal computeStockWorth(final String ticker, final int shares) {
    
          return priceFinder.apply(ticker).multiply(BigDecimal.valueOf(shares));
      }
  //... other methods that use the priceFinder ...


  public static void main(String[] args) {
    final CalculateNAV calculateNav = new CalculateNAV(YahooFinance::getPrice);
    
    System.out.println(String.format("100 shares of Google worth: $%.2f",
      calculateNav.computeStockWorth("GOOG", 100)));
  }
}

我的领域问题在某种程度上与教授试图做的非常相似。

我的 Spring 应用程序 ( InvoiceTour, InvoiceLabTest, InvoicePenatly) 中有三个实体。它们具有不同的属性并且没有任何关系,因此没有继承,没有接口。但我确实需要将它们发送到某个 SOAP Web 服务,该服务将为InsertInvoiceResponse每个实体返回相同的对象类型 ()。类SoapHelper很像YahooFinance

public class SoapHelper {
    
    public InsertInvoiceResponse getValueForTour(InvoiceTour invoiceTourEntity, Company company) {

        //Some processing of passed parameters which results in InsertInvoiceRequest (requestPayload) object (stub for soap service)

        return send(requestPayload);
    }

    public InsertInvoiceResponse getValueForLabTest(InvoiceLabTest invoiceLabTestEntity, Company company) {

        //Some processing of passed parameters which results in InsertInvoiceRequest (requestPayload) object (stub for soap service)

        return send(requestPayload);
    }

    public InsertInvoiceResponse getValueForPenalty(InvoicePenalty invoicePenalty Entity, Company company) {

        //Some processing of passed parameters which results in InsertInvoiceRequest (requestPayload) object (stub for soap service)

        return send(requestPayload);
    }
}

方法send(requestPayload)是这样的:

//Spring's abstraction for sending SOAP requests
public InsertInvoiceResponse send(InsertInvoiceRequest requestPayload) {
    return (InsertInvoiceResponse) getWebServiceTemplate()
    .marshalSendAndReceive("https://clienttesthorizon.horizonafs.com/AFSServices/AFSService.svc/basicHttpBinding", 
            requestPayload, new SoapActionCallback("http://tempuri.org/IAFSService/InsertInvoice")); 
}

我做了什么?

首先我创建了功能接口,如下所示:

@FunctionalInterface
public interface Executor<A,B,C> { //A - stands for any InvoiceXXX; B - Company parameter and C will be result of soap response (InsertInvoiceResponse)
    
    C apply(A a, B b);
}

接下来,我创建了一个类,该类负责使用方法引用调用实际的方法实现。类SoapCaller很像CalculateNAV。将SoapCaller有类型的私有字段Executor,但我想让它更通用。我确实知道界面本身已经是通用的,但是由于缺少文字,我不确定如何表达不同。

我的想法是能够传递给这样的构造函数SoapCaller

   public class SoapCaller {
    
        private Executor<A, B, C> exec;
        
        public SoapCaller(final Executor<Class<T> t, Class<F> f, Class<E> e> execGeneric) {
            this.exec = execGeneric;
        }
        
        public InsertInvoiceResponse callWebService(Class<T> t,  Class<F> f) {
            
          return exec.apply(t, f);
        }
        
    }

我的客户端代码应该是这样的:

public static void main(String[] args) {
    
    InvoiceTour it = db.getInvoiceTour();
    InvoiceLabTest ilt = db.getInvoiceLabTest();
    InvoicePenalty ip = db.getInvoicePenalty();
    
    Company c = db.getCompany();
    
    SoapCaller soapCallerForInvoiceTour = new SoapCaller(SoapHelper::getValueForTour);
    
    InsertInvoiceResponse invoiceTourResponse = soapCallerForInvoiceTour.callWebService(it, c);
    
    //do what ever with invoiceTourResponse
    
    SoapCaller soapCallerForInvoiceLabTest= new SoapCaller(SoapHelper::getValueForLabTest);
    
    InsertInvoiceResponse invoiceLabTestResponse = soapCallerForInvoiceTour.callWebService(ilt, c);
    
    //do what ever with invoiceLabTestResponse
    
}

当然,也有编译错误的基调。我不确定如何实现使功能接口更通用,然后它已经是(如果这有任何意义)?有谁知道如何使用 lambdas 和方法引用使其更具可读性?

标签: javagenericslambdastreammethod-reference

解决方案


如果我理解你,你希望SoapCaller(委托给 lambda 的类)也是通用的,所以它可以定义如下:

class SoapCaller<T, U> {

    private BiFunction<T, U, InsertInvoiceResponse> soapExecutor;
    
    public SoapCaller(final BiFunction<T, U, InsertInvoiceResponse> soapExecutor) {
        this.soapExecutor= soapExecutor;
    }
    
    public InsertInvoiceResponse callWebService(T t, U u) {
      return soapExecutor.apply(t, u);
    }
    
}

请注意,您可以使用 aBiFunction而不是定义自己的功能接口。

然后你可以按如下方式使用它:

SoapCaller<InvoiceTour, Company> soapCallerForInvoiceTour = new SoapCaller<>(SoapHelper::getValueForTour);
InsertInvoiceResponse invoiceTourResponse = soapCallerForInvoiceTour.callWebService(it, c);
    
//do what ever with invoiceTourResponse
    
SoapCaller<InvoiceLabTest, Company> soapCallerForInvoiceLabTest= new SoapCaller<>(SoapHelper::getValueForLabTest);
InsertInvoiceResponse invoiceLabTestResponse = soapCallerForInvoiceLabTest.callWebService(ilt, c);

您可以使用泛型参数,例如,如果您知道它Company不会改变,那么您可以删除类型参数:

class SoapCaller<T> {

    private BiFunction<T, Company, InsertInvoiceResponse> soapExecutor;

    ...
}

推荐阅读