具有 lambda 的相似函数的设计模式

我试图找出一种方法或模式来简化我的 Service 类并使其非常可调。我的目标是让 Service 类中的方法可以被访问,例如使用 lambdas 或 Predicates。


class Client {

  @RequestLine("something/a")

  public A fetchA() {}


  @RequestLine("something/b")

  public B fetchB() {}


  //... lots of similar methods


  @RequestLine("something/z")

  public Z fetchZ() {}

}


class Service {


 Client client;


 public void fixA(){

  client.fetchA();

  method();

 }


 public void fixB(){

  client.fetchB();

  method();

 }


// ... lots of similar methods


 public void fixZ(){

  client.fetchZ();

  method();

 }


 void method() {}


}

所以我的观点是如何更改它,以便它使用 lambdas 或其他可以让我的 Service 类使用“修复”方法之一的东西,但它会知道我需要从我的客户端获取什么。


如果这个问题很糟糕并且不符合这里的规则,那么请指出我正确的方向,因为我迷路了。


料青山看我应如是
浏览 169回答 3
3回答

守着星空守着你

我想你想要的是class Service {&nbsp; &nbsp; private Client client;&nbsp; &nbsp; public void fix(Consumer<Client> consumer){&nbsp; &nbsp; &nbsp; &nbsp; consumer.accept(client);&nbsp; &nbsp; &nbsp; &nbsp; method();&nbsp; &nbsp; }&nbsp; &nbsp; private void method() {}}您可以使用service.fix(Client::fetchB);

繁星点点滴滴

这个问题可能有点基于意见,但让我们试一试。在我看来,您制造的第一个设计缺陷是将所有fetchXYZ方法都放在一个客户端中。你可以创建一个Client看起来像这样的界面interface Client<T> {&nbsp; T fetch();}并像这样创建这个接口的实现:public class ClientA implements Client<A> {&nbsp; @RequestLine(”something/a“)&nbsp; public A fetch() {&nbsp; &nbsp; // do fetch stuff&nbsp; }}您可以将客户端实现的实例本地存储在地图中,或者使用工厂模式根据您的输入创建正确的客户端。最后fix,您的服务中的方法可能如下所示:public void fix(String clientType) {&nbsp; // returns instance of ClientA for ’a‘ for example&nbsp; final Client client = getClientForType(clientType);&nbsp; client.fetch();&nbsp; method();}可能有很多方法可以解决您的需求,这只是其中之一。我个人不喜欢传球的客户端功能作为参数传递给你的方法的想法(虽然你问它),在当前的设计Client有不同的责任(取A,B依此类推)。使用 lambda 表达式实际上强化了这个缺陷,并且进一步隐藏了Client实际作用。只有我的 2 美分。

largeQ

一种方法是将调用作为服务方法的参数传递给您的客户端。你需要使用泛型:class Service {&nbsp; &nbsp; Client client;&nbsp; &nbsp; public <T> void fix(Function<Client, T> clientCall) {&nbsp; &nbsp; &nbsp; &nbsp; T result = clientCall.apply(client);&nbsp; &nbsp; &nbsp; &nbsp; // Do something with result&nbsp; &nbsp; &nbsp; &nbsp; method();&nbsp; &nbsp; }}您需要fix按如下方式调用您的服务方法:service.fix(Client::fetchA);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java