简体   繁体   中英

What is the best way to design/process in Java 8 ordered calls on different methods

My question is regarding design

I'm trying to design order/sequential calls based on different methods.

Suppose my Class :

public class Foo {

    public Object method1(String a){
        // impl1..
    }


    public Object method2(List<Object> list){
        // impl2..
    }

    public Object method3(Map<String,String> map, Object otherStuff){
        // impl3..
    }

    // other different methods ....
}

I want to follow this concept http://qrman.github.io/posts/2017/02/09/pipeline-pattern-plumber-quest

But my difference is that I use the only 1 class with multiple methods, if i had different services I would create new class to each service with interface implementation as in the link , but my purpose is create list of order methods inside 1 class that will iterate and execute them...

I was thinking about some method reference based on java 8

like described here : https://www.codementor.io/eh3rrera/using-java-8-method-reference-du10866vx

basic idea ?

List<> list = new ArrayList<>();
list.add(Foo::method1)
list.add(Foo::method2)
list.add(Foo::method3) ...

forEach ..list -> execute

Thanks a lot

Because formal and actual arguments vary from one method to the other, you cannot use method reference. Lambdas should do the job:

    List<Consumer<Foo>> list = new ArrayList<>();
    list.add((foo) -> foo.method1("a"));
    list.add((foo) -> foo.method2(new ArrayList<>()));
    list.add((foo) -> foo.method3(new HashMap<>(), "Other stuff"));

    Foo foo = new Foo();
    list.forEach(fooConsumer -> fooConsumer.accept(foo));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM