如何在 Java 中创建链式方法

我有一个类负责控制在运行时创建的对象——它根据摆动框架的输入构建它们——就像一个 DAO。它具有删除已创建对象的方法:


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);

        }

    }

}

我不希望调用此方法并传递所指类和索引,而是希望方法调用是这样的:dao.removeFrom(MyObject.class).at(myIndex);猜猜它看起来像 Stream API 使用的链式方法。很高兴有人能帮助我!


幕布斯7119047
浏览 209回答 3
3回答

九州编程

在这种情况下,您的removeFrom()方法应该返回围绕((ArrayList<Object>) entry.getValue()).&nbsp;并且该包装器必须具有at(int index)删除给定索引的元素的方法。并且您还需要考虑当您modelsMap没有给定clazz.

千巷猫影

请检查 Builder 设计模式。尝试为一个简单的对象创建构建器设计模式,该对象几乎没有属性以及 getter 和 setter。一旦你能够做到这一点,方法链就会看起来非常清晰。:)

慕尼黑5688855

您可以引入一个 DaoRemover 类,您可以通过工厂方法实例化该类,并且实例方法返回当前实例。例如 :public class DaoRemover {&nbsp; &nbsp; private Map<String, Object> modelsMap; // your actual data&nbsp; &nbsp; private final List<ArrayList<Object>> list; // list of list after filtering on the class&nbsp; &nbsp; public static DaoRemover of(Class<?> clazz) {&nbsp; &nbsp; &nbsp; &nbsp; return new DaoRemover(clazz);&nbsp; &nbsp; }&nbsp; &nbsp; private DaoRemover(Class<?> clazz) {&nbsp; &nbsp; &nbsp; &nbsp; list = modelsMap.entrySet()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(e -> e.getKey()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .equals(clazz.getSimpleName()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(e -> (ArrayList<Object>) e.getValue())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(toList());&nbsp; &nbsp; }&nbsp; &nbsp; public DaoRemover at(int index) {&nbsp; &nbsp; &nbsp; &nbsp; list.forEach(l -> l.remove(index));&nbsp; &nbsp; &nbsp; &nbsp; return this;&nbsp; &nbsp; }}你现在可以这样做:DaoRemover.of(MyObject.class)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .at(myIndex);&nbsp;或者DaoRemover.of(MyObject.class)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .at(myIndex)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .at(myOtherIndex);&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java