简体   繁体   中英

How to create chained methods in Java

I have a class responsible for controlling the objects created during runtime - it builds them from inputs at swing frames - just as a DAO. It has this method that removes already created objects:

public void removeFrom(Class<?> clazz, int index) {
    for (Map.Entry<String, Object> entry : modelsMap.entrySet()) {
        if (entry.getKey().equals(clazz.getSimpleName())) {
            ((ArrayList<Object>) entry.getValue()).remove(index);
        }
    }
}

Instead of calling this method and passing the referent class and index, I'd like the method call to be like this: dao.removeFrom(MyObject.class).at(myIndex); Guess it's looks like chained methods as the Stream API uses. Glad if anyone can help me!

In this case your removeFrom() method should return wrapper around ((ArrayList<Object>) entry.getValue()) . And that wrapper has to have method at(int index) which removes element for given index.

And you also need to think about corner case when your modelsMap doesn't have entry for a given clazz .

Please check on the Builder design pattern. Try creating builder design pattern for a simple object which has few attributes and getters and setters.

Once you are able to do that, method chaining will look very clear. :)

You could introduce a DaoRemover class that you can instantiate by a factory method and which the instance methods return the current instance.

For example :

public class DaoRemover {
    private Map<String, Object> modelsMap; // your actual data
    private final List<ArrayList<Object>> list; // list of list after filtering on the class


    public static DaoRemover of(Class<?> clazz) {
        return new DaoRemover(clazz);
    }

    private DaoRemover(Class<?> clazz) {
        list = modelsMap.entrySet()
                        .stream()
                        .filter(e -> e.getKey()
                                      .equals(clazz.getSimpleName()))
                        .map(e -> (ArrayList<Object>) e.getValue())
                        .collect(toList());
    }

    public DaoRemover at(int index) {
        list.forEach(l -> l.remove(index));
        return this;
    }

}

You could do now :

DaoRemover.of(MyObject.class)
          .at(myIndex); 

or

DaoRemover.of(MyObject.class)
          .at(myIndex) 
          .at(myOtherIndex); 

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