Design pattern for similar functions with lambdas

KompiKompi :

I am trying to figure out a way or a pattern to simplify my Service class and make it very adjustable. My aim would be for the method in Service class to be accessed for example with lambdas or 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() {}

}

So my point how I could change it so it would use lambdas or something that would leave my Service class with one of the "fix" methods but it would know what I need to fetch from my Client.

If this question is bad and does not comply with rules here then please point me in the right direction as I am lost.

Federico Peralta Schaffner :

One way would be to pass the call to your client as an argument to the method of your service. You'd need to use generics:

class Service {

    Client client;

    public <T> void fix(Function<Client, T> clientCall) {

        T result = clientCall.apply(client);

        // Do something with result

        method();
    }

}

You would need to call your service fix method as follows:

service.fix(Client::fetchA);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116133&siteId=1