[英]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: 您必须执行以下操作之一:
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.