简体   繁体   English

从抽象类的所有子类调用方法的最佳方法是什么?

[英]What is the best way to call methods from all the subclasses of an abstract class?

I want to make API calls to a bunch of different API services. 我想对一堆不同的API服务进行API调用。 I have an abstract class called ApiService that contains common methods for each subclass. 我有一个名为ApiService的抽象类,它包含每个子类的公共方法。 Every new API will have to inherit and implement these methods. 每个新API都必须继承并实现这些方法。

My question is: how can I go through all the subclasses of ApiService and call their methods? 我的问题是:如何通过ApiService所有子类并调用它们的方法?

Right now, I have a static array of all the services instantiated already (which means that new services must be manually added to the array) that looks something like this: 现在,我已经实例化了所有服务的静态数组(这意味着必须手动将新服务添加到数组中),如下所示:

ApiService[] services = {new SubService1(), new SubService2(), ...};

I was wondering if there was a better way of doing this. 我想知道是否有更好的方法来做到这一点。

You want to call a method on each instances of subclasses of an abstract class. 您想要在抽象类的每个子类实例上调用一个方法。 There is no automatic way to find all the instances of a class anyway, so you need to manage the list of all instances yourself. 无论如何都没有自动查找类的所有实例的方法,因此您需要自己管理所有实例的列表。

You have to do one of the following: 您必须执行以下操作之一:

  • manage the list manually, that is add instances to the list when you create them 手动管理列表,即在创建列表时将实例添加到列表中
  • make that more automated, by adding the instance to a static list in the constructor of your base class ApiService . 通过将实例添加到基类ApiService的构造函数中的静态列表,使其更加自动化。 But it makes the base class aware of the list of its instances, and it seems to me a bit of a code smell. 但它使基类知道它的实例列表,在我看来有点代码味道。

There is another alternative, when you know the number of instances in your application in advance: use an Enum instead of an abstract class. 当您事先知道应用程序中的实例数时,还有另一种选择:使用Enum而不是抽象类。 Each Enum value is an instance of the class, and it can implement interfaces and methods, and each instance can override a method differently. 每个Enum值都是类的一个实例,它可以实现接口和方法,每个实例都可以以不同方式覆盖方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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