Java中如何统一调用所有Interface_Updatable接口实现类的updateViewModel方法
实现方案
1. 基础集合批量调用(最简便)
将所有实现了Interface_Updatable接口的实例统一存入List<Interface_Updatable>类型的集合,遍历集合即可批量调用方法,后续新增实例只需添加到集合中,无需修改调用逻辑,避免漏调。
示例代码:
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { // 实例化各个实现类 Interface_Updatable impl1 = new 你的实现类1(); Interface_Updatable impl2 = new 你的实现类2(); Interface_Updatable impl3 = new 你的实现类3(); // 统一存入接口类型的集合 List<Interface_Updatable> updatableList = new ArrayList<>(); updatableList.add(impl1); updatableList.add(impl2); updatableList.add(impl3); // 批量调用方法(Java 8及以上支持方法引用写法) updatableList.forEach(Interface_Updatable::updateViewModel); // Java 8以下版本用普通for循环即可 // for (Interface_Updatable item : updatableList) { // item.updateViewModel(); // } } }
2. 注册中心模式(适合实例多、动态生成的场景)
如果实例是动态生成的,或者不想手动维护集合,可以单独做一个管理类统一注册、统一调用,完全解耦实例创建和批量调用逻辑:
// 统一管理类 public class UpdatableRegistry { private static final List<Interface_Updatable> REGISTRY = new ArrayList<>(); // 实例化后调用该方法注册 public static void register(Interface_Updatable updatable) { if (updatable != null) { REGISTRY.add(updatable); } } // 对外提供批量更新方法 public static void updateAll() { REGISTRY.forEach(Interface_Updatable::updateViewModel); } }
使用示例:
public class Main { public static void main(String[] args) { // 实例化后直接注册即可 UpdatableRegistry.register(new 实现类1()); UpdatableRegistry.register(new 实现类2()); UpdatableRegistry.register(new 实现类3()); // 需要批量调用时执行这一行即可 UpdatableRegistry.updateAll(); } }
内容的提问来源于stack exchange,提问作者dev.niho
相关产品推荐
相关产品推荐

